Given the following data class:
data class Coords(val x: Int, val y: Int) {
companion object CoordsOps {
private val shiftTable: Map<Direction, Pair<Int, Int>> = mapOf(
Direction.North to Pair(0, 1),
Direction.East to Pair(1, 0),
Direction.South to Pair(0, -1),
Direction.West to Pair(-1, 0)
)
private operator fun Coords.plus(increment: Pair<Int, Int>): Coords =
Coords(x + increment.first, y + increment.second)
fun Coords.shift(direction: Direction): Coords = this + shiftTable.getValue(direction)
}
}
I'm not able to use the extension function shift()
from outside that object. I would like to use Coords.shift(direction)
.
What am I doing wrong?
You should be able to. I copied your code exactly and was able to call extension function shift from another file.
Perhaps you're missing the import? Or calling it incorrectly? Try this
import <your_package>.Coords.CoordsOps.shift
val y = Coords(3, 4).shift(Direction.East)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.