4

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

2 Answers 2

2

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?

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

this works. Although if it's not too much, can you explain why does this work?
Why is answered by @thoredge in his ans.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.