Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop kotlin类构造函数参数的默认值类型是什么?_Oop_Kotlin - Fatal编程技术网

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

Oop kotlin类构造函数参数的默认值类型是什么?,oop,kotlin,Oop,Kotlin,但当我添加var或val时 Unresolved reference: name 或 然后程序工作正常,所以为什么我需要在name中添加var或val,构造函数参数val或var的默认类型是什么,为什么当我没有提到var或val时程序会给我错误,要在类Greeter(name:String)这样的构造函数中使用值,可以使用init{} Unresolved reference: name class Greeter(val name: String) { 或者,如果在构造函数中使用val或

但当我添加var或val时

Unresolved reference: name


然后程序工作正常,所以为什么我需要在name中添加var或val,构造函数参数val或var的默认类型是什么,为什么当我没有提到var或val时程序会给我错误,要在类Greeter(name:String)这样的构造函数中使用值,可以使用init{}

Unresolved reference: name
class Greeter(val name: String) {
或者,如果在构造函数中使用val或var,它更像是类级别的变量,可以在类中的任何位置访问

class Greeter(name: String) {
    var string:name = ""
    init{
        this.name = name
    }

   fun greet() {
       println("Hello, $name")
    }
}
然后可以在类中直接使用变量名。
在这两种情况下,我们也可以为变量提供默认值。

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

错误的方式:

class Greeter(var name:String){
    fun greet() {
       println("Hello, $name")
    }
}
正确的方式:

// 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
}

您还可以将
val
替换为
var
,使
名称
成为
可变的
类成员。

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

内部访问,因为添加
val
var
也会使参数成为属性。如果没有任何一个关键字,参数只是一个参数,因此只能在初始化期间访问。请参阅“您必须使用init{}”不,您不需要,它也可以直接在初始值设定项中使用(
var\u name=name
)。
// 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
}