LoginSignup
2
0

More than 5 years have passed since last update.

Kotlin 1.1 BetaでShorter syntax for propertiesを用いるときの注意点

Last updated at Posted at 2017-01-30

Kotlin 1.1にて導入される構文の1つである Shorter syntax for properties を用いた以下のようなコードは,1.1.0-beta-22の段階では構文チェックは通るもののコンパイル時に落ちます.


open class A(val s: String)

class B(s: String): A(s) {
    val rep // ここが問題
        get() = s.replace("a", "b")
}

fun main(args: Array<String>) {
    println(B("abrakadabra").rep)
}
Error:Kotlin: [Internal Error] org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Don't know how to generate outer expression for lazy class B
︙

問題の箇所は

val rep: String
    get() { return s.replace("a", "b") }

と等価になるはずなのでsthis.sのつもりで使用していますが,コンストラクタに渡されたsと判別がつかないためにエラーを吐くようです.

対処法としては,

  1. repの型を明記する
  2. コンストラクタの引数名を変更する
  3. this.sに書き換える

が考えられます.
本質的にはrepの型を推定するプロセスの問題なので,通常は型を明記すれば良いでしょう.
(多少はコンパイル速度も向上するのではないかと思いますし)

修正後のBクラスのコードは次のようになります.

class B(s: String): A(s) {
    val rep: String // 変更点
        get() = s.replace("a", "b")
}

~2017/2/3追記~
バグ報告は既にされているので,そのうち修正されると思います.
https://youtrack.jetbrains.com/issue/KT-15844

2
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
2
0