简体   繁体   中英

Scala implicit method parameters

In the following code snippet below:

scala> class A
defined class A

scala> class B extends A
defined class B

scala> def t(b: B)(implicit a: A) = println(a)
t: (b: B)(implicit a: A)Unit

scala> val b = new B
b: B = B@7746d2

scala> t(b)
<console>:12: error: could not find implicit value for parameter a: A
              t(b)
               ^

scala> val c = new B
c: B = B@4fa2e041

scala> t(b)
<console>:12: error: could not find implicit value for parameter a: A
              t(b)
               ^

scala> 

The sub type is there in the scope, so why would it fail compilation?

You need to declare a val as implicit for it to be usable in implicit parameters :

scala> val b = new B
b: B = B@38cccef

scala> t(b)
<console>:12: error: could not find implicit value for parameter a: A
              t(b)
               ^

scala> implicit val c = new B
c: B = B@6d00a15d

scala> t(b)
$line4.$read$$iw$$iw$B@6d00a15d

You have to declare an implicit value of type A (or B since B extends A).

implicit val a = new A

and then your t(b) should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM