通过在Kotlin中进行销毁来初始化val [英] Initialization of val by destructuring in Kotlin

查看:403
本文介绍了通过在Kotlin中进行销毁来初始化val的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初我想实现

class NotationDiceRoll(notation: String) {
    val rolls: Int
    val sides: Int

    init {
        parseNotation(notation)
    }

    private fun parseNotation(notation: String) {
        rolls = 1
        sides = 4
    }
}

但是Kotlin抱怨无法重新分配Val".

But Kotlin complains that "Val cannot be reassigned".

似乎可以分配val的唯一地方是init块.好吧,毕竟这更加明显.所以我将其更改为

It seems that the only place where the vals can be assigned is the init block. Alright then, it is more obvious after all. So I changed it to

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)
    }
}

现在,科特林抱怨必须初始化变量卷"".

Now Kotlin complains that "Variable 'rolls' must be initialized".

可以解决

init {
    val(rolls, sides) = parseNotation(notation)

    this.rolls = rolls
    this.sides = sides
}

但是不太优雅.

所以我的问题是:仅当在同一行上声明val时,解构真的可能吗?

So my question is: is the destructuring really possible only with the vals being declared on the same line?

推荐答案

此功能称为解构声明,这就是对新变量的声明,并立即为其分配变量.不仅是用val声明的变量不能在以后的解构中使用,更早的声明的变量也不能用.例如,以下方法也不起作用:

This feature is called a destructuring declaration, and that's what it is, a declaration of new variables with immediate assignment to them. It's not just that variables declared with val can't be used in later destructuring, no variables declared earlier can. For example, the following doesn't work either:

var x = 0
var y = 0
(x, y) = Pair(1, 2)

值得注意的是,您正在寻找的功能(销毁任务)是Kotlin未来可能使用的功能之一,在Kotlin 1.1赛事中可投票的20张卡中.不再进行在线调查时,您可以在

It's worth noting though that the feature you're looking for (destructuring assignments) was one of the possible future features for Kotlin out of the 20 cards that were available to be voted on at the Kotlin 1.1 event. While the online survey is no longer up, you can see the description of the feature on this image, it's card number 15. It's a bit hard to make out, so here's what's on it:

科特林已经有销毁声明:

Kotlin already has destructuring declarations:

val (name, address) = findPerson(...)

某些用户要求进行销毁分配, IE.分配给多个先前声明的var:

Some users request destructuring assignments, ie. assign to multiple previously declared var's:

var name = ...
...
var address = ...
...
(name, address) = findPerson(...)

您需要此功能吗?

更新:这是具有建议功能的官方文档,并且这是调查结果.

这篇关于通过在Kotlin中进行销毁来初始化val的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆