2016-11-24 117 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