小编sel*_*fud的帖子

Scala隐式参数,默认值在随播对象中定义

根据Scala Spec(2.8),对于要发现的隐式,它必须在本地范围,继承范围或伴随对象中定义.鉴于此,在我看来,下面的代码应该没有明确导入伴随对象的内容.我在Scala库源中看到了这个(例如CanBuildFrom).似乎我应该能够从XX类的定义之外调用XX.foo()并使用我所使用的伴随类中的隐式参数.我错过了什么?

object XX {
   implicit def XYZ[T]: (T) => Unit = null
}

class XX {
  // import XX._     // Works with this line uncommented...
  def foo(s: String)(implicit f: (String) => Unit): Unit = {
    if (f == null)
      println("Just: " + s)
    else
      f(s)
  }

  def bar {
    foo("abc"){ s => println("Func: " + s)}
    foo("xyz")  // <-- Compile error here: could not find implicit value for parameter f
  }
}
Run Code Online (Sandbox Code Playgroud)

scope scala implicit

7
推荐指数
1
解决办法
2030
查看次数

标签 统计

implicit ×1

scala ×1

scope ×1