最初我想实现
class NotationDiceRoll(notation: String) {
val rolls: Int
val sides: Int
init {
parseNotation(notation)
}
private fun parseNotation(notation: String) {
rolls = 1
sides = 4
}
}
但Kotlin抱怨说“Val无法重新分配” .
似乎唯一可以分配val的地方是init块 . 好吧那么,毕竟更加明显 . 所以我改成了
class NotationDiceRoll(notation: String) {
val rolls: Int
val sides: Int
init {
(rolls, sides) = parseNotation(notation)
}
private fun parseNotation(notation: String): Pair<Int, Int> {
return Pair(1, 4)
}
}
现在Kotlin抱怨“必须初始化”变量'卷' .
它可以解决
init {
val(rolls, sides) = parseNotation(notation)
this.rolls = rolls
this.sides = sides
}
但它不那么优雅 .
所以我的问题是:只有在同一行上声明vals时,解构才真正可行吗?
1 回答
此功能称为destructuring declaration,就是这样,它是一个立即分配给它们的新变量 declaration . 使用
val
声明的变量不仅可以起作用:它正在寻找(解构作业)是Kotlin可能在Kotlin 1.1活动中投票的20张牌中可能的未来特征之一 . 虽然在线调查不再起作用,但您可以在this image上看到该功能的描述,它有点难以辨认,所以这里有's what':
15解构任务
Kotlin已经有了解构声明:
一些用户请求解构分配,即 . 分配给多个先前声明的
var
:你需要这个功能吗?
更新:here's an official doc with the proposed features和here's the survey results .