字符串模板中不能识别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的输出与第三个输出相同。 我试图得到模板中列表的最后一个元素,它工作正常(第二个输出),所以是一个错误或我缺少一些使用扩展属性时的东西?
我正在使用kotlin 1.0.5
你需要用大括号包装你的模板属性,就像你用list.last()
。
println("the last index is ${list.lastIndex}")
没有花括号,它只能识别list
作为模板属性。
Kotlin编译器需要以某种方式解释string
来构建一个StringBuilder
表达式 。 由于您使用的是.
表达式需要被包装在${..}
以便编译器知道如何解释它:
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()
结果。