views:

218

answers:

2

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

+10  A: 

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)

IttayD
+5  A: 

You have to specify which var or val will be used as the implicit value:

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> new A
res0: A = A@16b18b6

scala> res0.c
res1: Int = 10

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