为什么隐式参数的Scala示例不起作用?

时间:2010-04-25 15:07:37

标签: scala language-features scala-2.8

简单的REPL测试......

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

为什么这些尝试用法都不起作用?

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) }
                                     ^

由于

2 个答案:

答案 0 :(得分:14)

您需要将A定义为隐含在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

通常,只考虑定义为implicits的值/方法,并在范围内或在所需类型的伴随对象中搜索它们(在本例中为Int)

答案 1 :(得分:6)

您必须指定将使用哪个var或val作为隐式值:

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