0

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.
2
  • 1
    Dont use null then, use Option: case class Person(name: Option[String]=None, age:Option[Int] = None) and then you dont need all those boiler plate constructors Commented Aug 12, 2016 at 12:36
  • Firstly, as @maress said, it's not scala way to use null. Secondly, you can't assign null to Short (AnyVal) value. Commented Aug 12, 2016 at 12:38

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

I have one doubt, this(name, None); in this expression, what is the None means? Is it a value defined somewhere, or it created an object of type None?
Here is a link from the documentation explaining what Options are.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.