2016-11-24 64 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輸出預計將與第三之一。我試圖獲得模板中列表的最後一個元素,它工作正常(第二個輸出),所以是一個錯誤或我缺少一些使用擴展屬性時的東西?

我使用科特林1.0.5

回答

5

你需要用你的模板屬性在大括號中,就像你與list.last()一樣。

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

沒有花括號,它只能識別list作爲模板屬性。

+0

謝謝,它的工作!公認。 – lopushen

4

Kotlin編譯器需要以某種方式解釋string以構建StringBuilder expression。由於您使用的是.表達需要${..}被包裹的編譯器知道如何解釋它:

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