Home > Software engineering >  Expecting member declaration (this happens when using a variable from another class)
Expecting member declaration (this happens when using a variable from another class)

Time:10-29

The code here works:

fun main(){
    val pizza = random()
    print(pizza.num)
}

class random{
    val num = 5
}

But the code here does not work

fun main(){
    val pizza = random()
    print(pizza.num)
}

class random{
    val num = 5
    num = 7
}

The only difference is that in the last line of code I reassign the variable num. The only thing I did was change this variable from 5 to 7.

Why is this causing errors?

Note This is the online IDE I was using: https://developer.android.com/training/kotlinplayground

CodePudding user response:

2 things:

Firstly, you can't reassign vals. you need to change that to var

Secondly, you can't do assignments directly in a class body, only declarations. However, you could put it in an init block like this to get the desired result:

class random{
    var num = 5
    init {
        num = 7
    }
}

you might want to read the documentation about kotlin classes here

  • Related