在 Kotlin 中通过解构初始化 val
Initialization of val by destructuring in Kotlin
本来想实现
class NotationDiceRoll(notation: String) {
val rolls: Int
val sides: Int
init {
parseNotation(notation)
}
private fun parseNotation(notation: String) {
rolls = 1
sides = 4
}
}
但是 Kotlin 抱怨 "Val cannot be reassigned"。
好像只有init块可以给vals赋值了。好吧,毕竟更明显了。所以我改成了
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 抱怨 "Variable 'rolls' must be initialized"。
可以通过
解决
init {
val(rolls, sides) = parseNotation(notation)
this.rolls = rolls
this.sides = sides
}
但不够优雅
所以我的问题是:解构是否真的只有在同一行声明 val 时才有可能?
此功能称为 destructuring declaration,就是这样,声明 新变量并立即分配给它们。不仅仅是用 val
声明的变量不能在以后的解构中使用,之前声明的变量也不能。例如,以下内容也不起作用:
var x = 0
var y = 0
(x, y) = Pair(1, 2)
值得注意的是,在 Kotlin 1.1 活动中可供投票的 20 张卡片中,您正在寻找的功能(解构分配)是 Kotlin 未来可能的功能之一。网上调查没了,大家可以在this image上看到功能的描述,卡号是15,有点难辨认,下面是这样的:
15 次解构赋值
Kotlin 已经有解构声明:
val (name, address) = findPerson(...)
一些用户请求解构赋值,
IE。分配给多个先前声明的 var
's:
var name = ...
...
var address = ...
...
(name, address) = findPerson(...)
你需要这个功能吗?
更新:here's an official doc with the proposed features, and here's the survey results。
本来想实现
class NotationDiceRoll(notation: String) {
val rolls: Int
val sides: Int
init {
parseNotation(notation)
}
private fun parseNotation(notation: String) {
rolls = 1
sides = 4
}
}
但是 Kotlin 抱怨 "Val cannot be reassigned"。
好像只有init块可以给vals赋值了。好吧,毕竟更明显了。所以我改成了
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 抱怨 "Variable 'rolls' must be initialized"。
可以通过
解决init {
val(rolls, sides) = parseNotation(notation)
this.rolls = rolls
this.sides = sides
}
但不够优雅
所以我的问题是:解构是否真的只有在同一行声明 val 时才有可能?
此功能称为 destructuring declaration,就是这样,声明 新变量并立即分配给它们。不仅仅是用 val
声明的变量不能在以后的解构中使用,之前声明的变量也不能。例如,以下内容也不起作用:
var x = 0
var y = 0
(x, y) = Pair(1, 2)
值得注意的是,在 Kotlin 1.1 活动中可供投票的 20 张卡片中,您正在寻找的功能(解构分配)是 Kotlin 未来可能的功能之一。网上调查没了,大家可以在this image上看到功能的描述,卡号是15,有点难辨认,下面是这样的:
15 次解构赋值
Kotlin 已经有解构声明:
val (name, address) = findPerson(...)
一些用户请求解构赋值,
IE。分配给多个先前声明的 var
's:
var name = ...
...
var address = ...
...
(name, address) = findPerson(...)
你需要这个功能吗?
更新:here's an official doc with the proposed features, and here's the survey results。