以下是一个简单的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
字段的要求相同。答案 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.