Kotlin,带有属性的字符串模板

时间:2018-03-08 21:15:55

标签: android kotlin

我正在学习Kotlin。我有以下代码:

Received: 'Hello World (1)!'
(other work in progress)
Received: 'Hello World (2)!'
(other work in progress)
Received: 'Hello World (3)!'
Received: 'Hello World (4)!'
(other work in progress)
Received: 'Hello World (5)!'
(other work in progress)
Received: 'Hello World (6)!'
(other work in progress)
Received: 'Hello World (7)!'
Received: 'Hello World (8)!'
(other work in progress)
Received: 'Hello World (9)!'
(other work in progress)
Received: 'Hello World (10)!'
Output pipe: End of file
Child exited with code=0(Success)
(Operation canceled)

此代码不起作用,在编译期间出错。问题是:如何在Kotlin的字符串模板中使用属性值? TNX

1 个答案:

答案 0 :(得分:9)

因为您声明了构造函数参数,而不是属性。您必须将其声明为valvar

class Person(val name: String, val surname: String) {

}

如果你离开valvar,Kotlin将它们视为构造函数本身的参数。它们可以在任何字段初始化器或初始化块中使用,但它们不会被声明为属性。