[英]Implicit resolution from trait
我有一個類似於以下情況的用例:
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))
我明白我需要將特征中定義的x
定義在B的隱式范圍內。我已經嘗試過以下內容:
# 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來說還是新手)。
將整個代碼包裝在一個對象中並擴展class B
trait 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-line中解析,但不可用。 您在類的主體中隱式可用變量,但那里不需要隱式String的解析。
隱含不是魔術; 如果你無法明確地到達隱式變量,那么編譯器也不能。
你真的想解決什么問題?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.