Eric
Eric

Reputation: 24880

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:

Upvotes: 0

Views: 1020

Answers (1)

John K
John K

Reputation: 1285

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.

Upvotes: 1

Related Questions