1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Kotlin]メンバ変数に対する分解宣言時のエラー

Last updated at Posted at 2022-04-03

分解宣言

Kotlinでは、分解宣言という仕組みがあるが、代入先はローカル変数のみが可能で、
メンバ変数の場合、以下のエラーが発生する。

Destructuring declarations are only allowed for local variables/values

動作環境

  • Kotlin 1.6.10

エラーが発生する例

data class Data(
	val data1: String,
	val data2: String,
	val data3: String
)

class Test {
    // メンバ変数のため分解宣言不可
    val (test1, test2, test3) = Data("string1", "string2", "string3")
    
    fun print() {
        print("${test1}, ${test2}, ${test3}")
    } 
}

fun main() {
    val test = Test()
    test.print()
}

エラーが発生しない例

data class Data(
	val data1: String,
	val data2: String,
	val data3: String
)

class Test {
    fun print() {
        // ローカル変数のため分解宣言可能
        val (test1, test2, test3) = Data("string1", "string2", "string3")
        print("${test1}, ${test2}, ${test3}")
    }
}

fun main() {
    val test = Test()
    test.print()
}

discuss.kotlinlang.orgにはトピックとして挙がっているが、特に回答はなく、不可である理由は不明。
(日本語での情報も特にないので、もしかすると当たり前の常識なのかもしれない?)

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?