Kotlin 类构造函数参数的默认值类型是什么?


class Greeter(name: String) {
fun greet() {
println("Hello, $name")
}
}
fun main(args: Array<String>) {
Greeter(args[0]).greet()
}

对于上面的程序,我得到了这个错误

Unresolved reference: name

但是当我添加 var 或 val 时

class Greeter(var name: String) {

class Greeter(val name: String) {

然后程序工作正常,所以为什么我需要在名称中添加 var 或 val,构造函数参数 val 或 var 的默认类型是什么,以及为什么当我不提到 var 或 val 时程序给我错误

要在构造函数中使用你的值,比如类 Greeter(name: String(,你可以使用 init{}

class Greeter(name: String) {
var string:name = ""
init{
this.name = name
}
fun greet() {
println("Hello, $name")
}
}

或者如果你在构造函数中使用val或var,它更像是类级变量,可以在类中的任何位置访问

class Greeter(var name:String){
fun greet() {
println("Hello, $name")
}
}

然后,变量名可以直接在类中使用。 在这两种情况下,我们还可以为变量提供默认值。

添加 val 或 var 会使参数成为属性,并且可以在整个类中访问。 没有这个,它只能在 init{} 内部访问

这个问题没有任何意义,但你面临的问题确实有意义。在您的情况下,您使用的方法是,

错误的方式:

// here name is just a dependency/value which will be used by the Greeter
// but since it is not assigned to any class members,
// it will not be accessible for member methods 
class Greeter(name: String) {
fun greet(){} // can not access the 'name' value
}

正确的方式:

// here name is passed as a parameter but it is also made a class member
// with the same name, this class member will immutable as it is declared as 'val'
class Greeter(val name: String) {
fun greet(){} // can access the 'name' value
}

还可以将val替换为var,以使name成为mutable类成员。

最新更新