So I want to access isInBounds
Navigation.kt:
data class Coordinate(val x:Int , val y:Int){
val isInBounds = x >= 0 && y >= 0
operator fun plus(other:Coordinate) = Coordinate(x + other.x, y + other.y)
}
But when I try to access it I get an unresolved reference.
Game.kt
private fun move(directionInput: String) = try {
val direction = Direction.valueOf(directionInput.uppercase())
val newPosition = direction.updateCoordinate(player.currentPosition)
if (!newPosition.isInBounds){
}
else{
}
} catch (e: Exception){
}
enum class Direction(private val coordinate: Coordinate){
NORTH(Coordinate(0 , -1)),
EAST(Coordinate(1 , 0)),
SOUTH(Coordinate(0 , 1)),
WEST(Coordinate(-1 , 0));
fun updateCoordinate(playerCoordinate:Coordinate) {
coordinate + playerCoordinate
}
}
The mistake is in
Direction
. Note that you did not specify a return type forupdateCoordinate
, and you used a block body for it. This means that it implicitly returnsUnit
. SoupdateCoordinate
calculatescoordinate + playerCoordinate
, discards the result, and returnsUnit
. This causesnewPosition
to beUnit
, and that is obviously not going to be have anisInBounds
property.Clearly that is not what you want. You should instead declare
updateCoordinate
with an expression body:or if you like block bodies:
This is just my opinion, but I think it is more readable to have
updateCoordinate
as a method onCoordinate
, calledmovedTowards
: