Eric Wang Eric Wang - 3 months ago 10
Scala Question

Constructor use null value as parameter

Following is a simple

scala
class definition, there are 2 constructors defined inside Person class.

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;


The question is:


  • When
    age
    field is not provided in constructor's argument list, I want to initialize it to null, not 0, what is the proper way to do that. Same requirement for the
    name
    field.


Answer

So basically the scala class you wanted to create is

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

Which returns

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.