Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Scala example of implicit parameter not working?

simple REPL test...

def g(a:Int)(implicit b:Int) = {a+b}

Why do neither of these attempted usages work?

1.

scala> class A { var b:Int =8; var c = g(2) }
:6: error: could not find implicit value for parameter b: Int
       class A { var b:Int =8; var c = g(2) }

2.

scala> class A(var b:Int) { var c = g(2) }  
:6: error: could not find implicit value for parameter b: Int
       class A(var b:Int) { var c = g(2) }
                                     ^

Thanks

like image 252
Alex R Avatar asked Apr 25 '10 15:04

Alex R


1 Answers

you need to define b as implicit in A

scala> def g(a:Int)(implicit b:Int) = {a+b}
g: (a: Int)(implicit b: Int)Int

scala> class A { implicit var b:Int =8; var c = g(2) }
defined class A

scala> val a = new A
a: A = A@1f7dbd8

scala> a.c
res3: Int = 10

In general, only values/methods that are defined as implicits will be considered and they are searched in scope, or in the companion object of the required type (Int in this case)

like image 131
IttayD Avatar answered Sep 27 '22 19:09

IttayD