gashu
gashu

Reputation: 492

Implicit resolution from trait

I have a use case similar to the situation following:

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

I understand that I need to bring x defined in the trait in the implicit scope of B. I've already tried the following:

# 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
}

Please explain what am I missing here (or, point me to relevant theory topic which I can study, fairly new to scala).

Upvotes: 4

Views: 116

Answers (2)

thoredge
thoredge

Reputation: 12621

The value of 'implicit y' will be resolved in your println-line where it is not available. You are making the variable implicitly available within the body of the class, but resolution of implicit String is not needed there.

Implicit isn't magic; if you can't reach the implicit variable explicitly then so can't the compiler.

What problem are you really trying to solve?

Upvotes: 2

curious
curious

Reputation: 2928

Wrap your whole code in a object and extend trait A in class B :

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

Output :

scala> P.f
3hello

Upvotes: 2

Related Questions