Question
Scala constructors FAQ: How do I create a Scala class with multiple constructors (secondary constructors)?
How-To
The Scala approach to defining multiple class constructors is a little different than Java, but somewhat similar. Rather than try to explain this in words, I just created some example source code to demonstrate how this works. Here's some source code to demonstrate the Scala "multiple constructors" approach:
- package demo
- object Main extends App {
- /**
- * The main/primary constructor is defined when you define your class.
- */
- class Person(val firstName: String, val lastName: String, val age: Int) {
- println("***Main Constructor***")
- /**
- * A secondary constructor.
- */
- def this(firstName: String) {
- this(firstName, "", 0);
- println("No last name or age given.")
- }
- /**
- * Another secondary constructor.
- */
- def this(firstName: String, lastName: String) {
- this(firstName, lastName, 0);
- println("No age given.")
- }
- override def toString: String = {
- return "%s %s, age %d".format(firstName, lastName, age)
- }
- }
- // (1) use the primary constructor
- val al = new Person("Alvin", "Alexander", 20)
- println(al)
- // (2) use a secondary constructor
- val fred = new Person("Fred", "Flinstone")
- println(fred)
- // (3) use a secondary constructor
- val barney = new Person("Barney")
- println(barney)
- }
Supplement
* [Scala IA] The Basics : Ch3. OOP in Scala - Classes and constructors
沒有留言:
張貼留言