程式扎記: [Scala 文章收集] How to create multiple class constructors in Scala

標籤

2016年9月5日 星期一

[Scala 文章收集] How to create multiple class constructors in Scala

Source From Here 
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: 
  1. package demo  
  2.   
  3. object Main extends App {  
  4.   /**  
  5.         * The main/primary constructor is defined when you define your class.  
  6.       */    
  7.   class Person(val firstName: String, val lastName: String, val age: Int) {    
  8.     println("***Main Constructor***")  
  9.       
  10.     /**  
  11.       * A secondary constructor.  
  12.       */    
  13.     def this(firstName: String) {    
  14.       this(firstName, ""0);    
  15.       println("No last name or age given.")    
  16.     }    
  17.       
  18.     /**  
  19.         * Another secondary constructor.  
  20.         */    
  21.     def this(firstName: String, lastName: String) {    
  22.       this(firstName, lastName, 0);    
  23.       println("No age given.")    
  24.     }    
  25.       
  26.     override def toString: String = {    
  27.       return "%s %s, age %d".format(firstName, lastName, age)    
  28.     }  
  29.   }  
  30.     
  31.   // (1) use the primary constructor    
  32.     val al = new Person("Alvin""Alexander"20)    
  33.     println(al)    
  34.     
  35.     // (2) use a secondary constructor    
  36.     val fred = new Person("Fred""Flinstone")    
  37.     println(fred)    
  38.     
  39.     // (3) use a secondary constructor    
  40.     val barney = new Person("Barney")    
  41.     println(barney)    
  42. }  
If you run this example program as is, you'll get the following output: 
***Main Constructor***
Alvin Alexander, age 20
***Main Constructor***
No age given.
Fred Flinstone, age 0
***Main Constructor***
No last name or age given.
Barney , age 0

Supplement 
[Scala IA] The Basics : Ch3. OOP in Scala - Classes and constructors

沒有留言:

張貼留言

網誌存檔