環境
Mac OS X 10.9.1
Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45).
概要
- 関数は引数名を指定して呼び出すことが出来る
- デフォルト引数のある関数との絡みが多い
- case classの一部のプロパティだけ変更した新しいインスタンスが欲しい
コード
scala> def division(x:Int, y:Int) = x / y
division: (x: Int, y: Int)Int
scala> division(50, 10)
res0: Int = 5
scala> division(y = 50, x = 10)
res1: Int = 0
scala> division(y = 10, x = 50)
res2: Int = 5
scala> def birth(year:Int, month:Int, day:Int, msg:String = "Your BirthDay is ") = {
| msg + "%d%d%d".format(year,month,day)
| }
birth: (year: Int, month: Int, day: Int, msg: String)String
scala> birth(2012,10,5)
res3: String = Your BirthDay is 2012105
scala> birth(1986,day=31,month=7)
res4: String = Your BirthDay is 1986731
scala> def birth(year:Int = 1986, month:Int = 1, day:Int = 1, msg:String = "Your BirthDay is ") = {
| msg + "%d/%d/%d".format(year,month,day)
| }
birth: (year: Int, month: Int, day: Int, msg: String)String
scala> birth()
res5: String = Your BirthDay is 1986/1/1
scala> birth(month=7)
res6: String = Your BirthDay is 1986/7/1
scala> case class X(a:Int, b:String)
defined class X
scala> val x = X(1, "Hello")
x: X = X(1,Hello)
scala> val x2 = x.copy(b = "copy hello")
x2: X = X(1,copy hello)
参考文献