构造函数使用null值作为参数

时间:2016-08-12 12:31:29

标签: scala constructor

以下是一个简单的scala类定义,在Person类中定义了2个构造函数。

Person.scala:

// class that has field and method,
class Person(var name:String, var age:Short) {
    def this() {
        this("", 0);
    }
    def this(name:String) {
        this(name, 0);
    }
    def hi() = printf("hi, I am %s!\n", name)
}

// var nobody = new Person();
var eric = new Person("Eric", 12);
eric.hi;

问题是

  • 当构造函数的参数列表中没有提供age字段时,我想将其初始化为null,而不是0,这是什么方法。对name字段的要求相同。

1 个答案:

答案 0 :(得分:1)

所以基本上你要创建的scala类是

case class Person(name:String, age:Option[Short] = None) {
    def hi() = println(s"hi, I am $name.\nMy age is ${age.getOrElse("not provided")}.")
}

返回

scala> var eric = new Person("Eric", Some(12));
eric: Person = Person(Eric,Some(12))

scala> eric.hi
hi, I am Eric.
My age is 12.

scala> var eric = new Person("Eric");
eric: Person = Person(Eric,None)

scala> eric.hi
hi, I am Eric.
My age is not provided.