by shigemk2

当面は技術的なことしか書かない

暗黙の引数

引数の前にimplicitキーワードをつけることでその引数が暗黙の引数になる。

scala> def sum(x:Int,y:Int,z:Int):Int = x + y + z
sum: (x: Int, y: Int, z: Int)Int

scala> sum(1,2,3)
res0: Int = 6

scala> def sum(x:Int)(y:Int)(z:Int):Int = x + y + z
sum: (x: Int)(y: Int)(z: Int)Int

scala> sum(1)(2)(3)
res1: Int = 6

scala> def greeting(name:String)(implicit greet:String) = {
     |   println(greet + name)
     | }
greeting: (name: String)(implicit greet: String)Unit

scala> greeting("taro")
<console>:9: error: could not find implicit value for parameter greet: String
              greeting("taro")
                      ^

scala> greeting("taro")("good morning!")
good morning!taro

scala> implicit val hello:String = "hello!"
hello: String = hello!

scala> greeting("taro")
hello!taro