【问题标题】:what is default value type of kotlin class constructor parameter?kotlin 类构造函数参数的默认值类型是什么?
【发布时间】:2019-12-14 04:25:30
【问题描述】:
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 时程序给我错误

【问题讨论】:

标签: oop kotlin


【解决方案1】:

要在类 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")
    }
}

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

【讨论】:

  • "你必须使用 init{}" 不,你不需要,它也可以直接在初始化器中使用 (var _name = name)。
【解决方案2】:

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

中访问

【讨论】:

    【解决方案3】:

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

    走错路:

    // 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 类成员。

    【讨论】:

      猜你喜欢
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      相关资源
      最近更新 更多