我已经开始尝试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
Run Code Online (Sandbox Code Playgroud)
我有以下输出
the last index is [1, 2, 3].lastIndex
the last element is 3
the last index is 2
Run Code Online (Sandbox Code Playgroud)
第一个println的输出预计与第三个println的输出相同.我试图在模板中获取列表的最后一个元素并且它工作正常(第二个输出),所以是一个bug或者我在使用扩展属性时遗漏了什么?
我正在使用kotlin 1.0.5
你需要将你的template-property包装成花括号,就像你一样list.last().
println("the last index is ${list.lastIndex}")
Run Code Online (Sandbox Code Playgroud)
没有花括号,它只能识别list为模板属性.
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |