2016-11-24 11 views
1

kotlinを試し始めましたが、質問が表示されました 私は可変リストの拡張プロパティを宣言し、この方法で文字列テンプレートで使用しようとしました:文字列テンプレートでKotlin拡張プロパティが認識されない

fun main(args: Array<String>) { 
    val list = mutableListOf(1,2,3) 
    // here if use String template the property does not work, list itself is printed 
    println("the last index is $list.lastIndex") 
    // but this works - calling method 
    println("the last element is ${list.last()}") 
    // This way also works, so the extension property works correct 
    println("the last index is " +list.lastIndex) 
} 

val <T> List<T>.lastIndex: Int 
    get() = size - 1 

と、私は次の出力

the last index is [1, 2, 3].lastIndex 
the last element is 3 
the last index is 2 

を持っている最初のprintlnの出力は、第三のものと同じであることが予想されます。テンプレートのリストの最後の要素を取得しようとしましたが、ok(2番目の出力)になってしまいました。これはバグか拡張プロパティを使用しているときに何か不足していますか?私はあなたがlist.last()で行ったよう、中括弧であなたのテンプレートプロパティをラップする必要が

答えて

5

1.0.5を使用していますkotlin

。中括弧なし

println("the last index is ${list.lastIndex}") 

、それが唯一のテンプレートプロパティとしてlist認識しています。

+0

ありがとうございました!受け入れられました。 – lopushen

4

StringBuilder expressionを作成するには、Kotlinコンパイラが何らかの方法でstringを解釈する必要があります。あなたは式がコンパイラの${..}に包まれる必要がある.を使用しているので、それを解釈する方法を知っている:

println("the last index is ${list.lastIndex}") // the last index is 5 

式を:

println("the last index is $list.lastIndex") 

println("the last index is ${list}.lastIndex") 
に相当します

したがって、list.toString()という結果がコンソールに表示されます。

+1

ありがとうございました! upvoted、以前の答えを受け入れる – lopushen

関連する問題