Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override an implicit value?

Suppose I have the code:

class A(implicit s:String = "foo"){println(s)}

object X {
   implicit val s1 = "hello"
}
object Y {
   import X._
   // do something with X
   implicit val s2 = "hi"
   val a = new A
}

I get the error:

<console>:14: error: ambiguous implicit values:
 both value s2 in object Y of type => String
 and value s1 in object X of type => String
 match expected type String
           val a = new A

Is there any way I can tell Scala to use the value s2 in Y? (if I rename s2 to s1, it works as expected but that is not what I want).

Another solution is to not do import X._, again something I'm trying to avoid.

like image 890
Jus12 Avatar asked Feb 28 '15 09:02

Jus12


People also ask

How do you pass an implicit parameter?

The implicit parameter in Java is the object that the method belongs to. It's passed by specifying the reference or variable of the object before the name of the method. An implicit parameter is opposite to an explicit parameter, which is passed when specifying the parameter in the parenthesis of a method call.

What is implicit in scala?

Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called.


1 Answers

Another thing you can do is to import everything but s1: import X.{s1 => _, _}.

like image 61
Alexey Romanov Avatar answered Oct 29 '22 04:10

Alexey Romanov