Search code examples
scalaimplicits

Shadow any2stringadd when implicitly converting Symbol


I am trying to implicitly add functions to the Symbol class through two levels of implicits (as described here). Consider the following code:

case class A(s: Symbol)
case class B(s: A) {
  def +[X](s: X)(implicit xtoa: X=>A) = B(xtoa(s))
}
implicit def xToB[X](s: X)(implicit xtoa: X => A) = B(xtoa(s))
implicit def symbolToA(s: Symbol) = A(s)

val x = 'a + 'b

This program does not compile:

Error: value + is not a member of Symbol

It seems that the problem is that instead of picking the implicits defined in the snipped, scala converts 'a with the any2stringadd function. In fact, the following two experiments seem to make the code compile:

  • I can use a different function name instead of + (like add for instance)
  • I can explicitly shadow any2stringadd in the imports: import Predef.{any2stringadd => _ , _}

I don't like either solution. My question is, is there any other way to rephrase my program to convince scala to select my implicits instead?

NB.: I'm using scala 2.12.1. Interestingly, IntelliJ does not complain about this snippet.


Solution

  • You can bring another thing named any2stringadd into scope.

    object myDsl {
      object any2stringadd
    
      case class A(s: Symbol)
      case class B(s: A) {
        def +[X](s: X)(implicit xtoa: X=>A) = B(xtoa(s))
      }
      implicit def xToB[X](s: X)(implicit xtoa: X => A) = B(xtoa(s))
      implicit def symbolToA(s: Symbol) = A(s)
    }
    
    import myDsl._
    val x = 'a + 'b