Implicit in Scala

// define a method that takes an implicit String
scala> def yo(implicit s:String) = println("Yo, " + s)
yo: (implicit s: String)Unit

// pass a string to it; it works
scala> yo("Adrian")
Yo, Adrian

// create an implicit String field, which is now "in scope"
scala> implicit val fred = "Fred"
fred: java.lang.String = Fred

// call yo without an argument; it magically finds fred(!)
scala> yo
Yo, Fred

// define an implicit field of a different type (Int)
scala> implicit val one = 1
one: Int = 1

// call yo again, see what happens (it finds fred again)
scala> yo
Yo, Fred

// define a second implicit String
scala> implicit val barney = "Barney"
barney: java.lang.String = Barney

// call yo again; now it can't figure out which String you want 
// it to implicitly use (fred or barney)
scala> yo
<console>:11: error: ambiguous implicit values:
 both value fred in object $iw of type => java.lang.String
 and value barney in object $iw of type => java.lang.String
 match expected type String
              yo
   


As you can see from the code, defining a method argument as implicit makes it like a magnet: If an implicit field of the same type is in scope, it pulls it right in ... with the limit that it can only deal with one implicit field of the matching type at one time.


转载自: http://alvinalexander.com/scala/scala-implicit-method-arguments-fields-example


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值