关于类属性的未解决的引用

时间:2019-01-26 23:31:10

标签: kotlin

我的代码:

open class Team (val country: String = "England",
            val aggressive: Boolean = true, 
             name: String, squadSize: Int = 24) {

    val attendance: Int

    init {
        if (aggressive){
            attendance = 25000
        } else {
            attendance = 20000
        }
    }

}

fun chooseTeam(team: String) {
    val homeTeam = Team(name = "Blue Team")
    println("the home team is ${homeTeam.name} so they are ${if(homeTeam.aggressive) "angry" else "timid" }")
}

我在Unresolved reference: name上得到了${homeTeam.name}

但是我在实例化类name时指定了val homeTeam = Team(name = "Blue Team")-知道为什么我得到未解决的引用吗?

1 个答案:

答案 0 :(得分:0)

在Kotlin中,您需要将val / var放在主构造函数内的任何属性之前,否则该属性将不会被声明为成员变量。

请更正:

open class Team(
    val country: String = "England",
    val aggressive: Boolean = true,
    val name: String,
    val squadSize: Int = 24
) {
   ...
}