Why is this Scala example of implicit parameter not working?
Asked Answered
B

2

8

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

Brendabrendan answered 25/4, 2010 at 15:7 Comment(0)
M
14

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)

Mardis answered 25/4, 2010 at 15:13 Comment(0)
S
6

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
Septet answered 25/4, 2010 at 15:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.