Kotlin继承接口的info4方法返回变量未成功赋值问题求助
问题原因
variable变量使用了val关键字声明:Kotlin中val代表只读常量,完成初始化赋值后就无法再次修改值,如果你需要后续修改变量内容,需要改用可写变量关键字var。info4方法中错误使用了比较运算符:你在when分支里用的==是判断两边值是否相等的比较运算符,并不会执行赋值操作,赋值需要使用单个等号=。
修正后的代码
class chooseRace(): adventuringBasics { // 把val改成var,支持后续修改 override var variable: String = " " override fun PrintOut() { println("Your race is $variable") } override fun info2(selects: String) { } override fun info6(lvl: Int) { } override fun info3(last: String) { } //Race Selector override fun info4(type: Int):String { when (type) { // 把==改成=,执行赋值操作 1 -> variable = "Human" 2 -> variable = "Orc" 3 -> variable = "Elf" 4 -> variable = "Demon Kin" 5 -> variable = "Beast Folk" else -> variable = "None Chosen" } return variable } override fun info5(selects: Int) { } }
内容的提问来源于stack exchange,提问作者Paulbatsantos Nathaniel
相关产品推荐
相关产品推荐

