Scala 特质的内隐分辨

Scala 特质的内隐分辨,scala,Scala,我有一个与以下情况类似的用例: trait A { implicit val x = "hello" } class B { // somehow bring x into scope here??? def run(x: Int)(implicit y: String) = y + x } println((new B).run(3)) # attempt 1 # class B extends A { .... } /// doesn't work # attempt

我有一个与以下情况类似的用例:

trait A {
  implicit val x = "hello"
}

class B {

  // somehow bring x into scope here???

  def run(x: Int)(implicit y: String) = y + x
}

println((new B).run(3))
# attempt 1 #
class B extends A { .... } /// doesn't work

# attempt 2 #
class B extends A {

  val x1 = implicitly[String]  /// doesn't work either

  def run(x: Int)(implicit y: String) = y + x
}
我知道我需要将trait中定义的
x
带到B的隐式范围中。我已经尝试了以下方法:

trait A {
  implicit val x = "hello"
}

class B {

  // somehow bring x into scope here???

  def run(x: Int)(implicit y: String) = y + x
}

println((new B).run(3))
# attempt 1 #
class B extends A { .... } /// doesn't work

# attempt 2 #
class B extends A {

  val x1 = implicitly[String]  /// doesn't work either

  def run(x: Int)(implicit y: String) = y + x
}

请解释我在这里遗漏了什么(或者,给我指出我可以学习的相关理论主题,对scala来说是相当新的)。

将您的整个代码包装在一个对象中,并在
类B中扩展
特征a

  object P {
    trait A {
      implicit val x = "hello"
    }
    class B extends A {
      def run(y: Int) = y + x
    }
   def f = println(new B().run(3))
  }
输出:

scala> P.f
3hello

“隐式y”的值将在println行中解析,但该行不可用。您正在使变量在类的主体内隐式可用,但不需要解析隐式字符串

含蓄不是魔法;如果不能显式地访问隐式变量,那么编译器也不能


你到底想解决什么问题?

这很有效。如果不是太多的话,你能解释一下为什么这样做吗?为什么在他的ans中用@thoredge来回答。