Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I access a val from a data class in kotlin?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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     
    } 
}

>Solution :

The mistake is in Direction. Note that you did not specify a return type for updateCoordinate, and you used a block body for it. This means that it implicitly returns Unit. So updateCoordinate calculates coordinate + playerCoordinate, discards the result, and returns Unit. This causes newPosition to be Unit, and that is obviously not going to be have an isInBounds property.

Clearly that is not what you want. You should instead declare updateCoordinate with an expression body:

fun updateCoordinate(playerCoordinate:Coordinate) =
    coordinate + playerCoordinate

or if you like block bodies:

fun updateCoordinate(playerCoordinate:Coordinate): Coordinate {
    return coordinate + playerCoordinate
}

This is just my opinion, but I think it is more readable to have updateCoordinate as a method on Coordinate, called moveTowards:

data class Coordinate(val x: Int, val y: Int) {
    operator fun plus(coord: Coordinate) = ...

    fun moveTowards(direction: Direction) =
        this + direction.coordinate // you'd have to make direction.coordinate public
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading