tribbloid
tribbloid

Reputation: 3838

In scala, is it possible to discourage the compiler from searching for Predef implicit first?

This post:

Where does Scala look for implicits?

described the implicit search precedence & algorithm used by modern scala compiler. In the above list, directly imported implicit functions should have higher precedence over scopes in associated types (e.g. defined in companion object)

This rule make sense most of the time, until the directly imported Predef.scala start to interfere:

    case class A(v: Int)

    object A {

      implicit class AFns(self: A) {

        def +(v2: Int): A = A(self.v + v2)
      }
    }

    val a1 = A(3)

    val b = a1 + 4

    assert(b == A(7))

The above example should compile successfully, but + operator override for ALL classes defined in Predef dominated the scene and caused all extensions with + operator to be useless (unless explicitly imported in a tighter scope). This is seriously annoying, is there a way to disable implicits in Predef or 'downgrade' its precedence?

The above experiment has been conducted in scala 2.12.12 & 2.13.3

Upvotes: 2

Views: 165

Answers (1)

user
user

Reputation: 7604

Importing A._ explicitly works, but you can also use -Yimports by adding this to your build.sbt to leave out the scala.Predef._ import:

scalacOptions ++= Seq("-Yimports", "java.lang", "scala")

After that, you can import everything from Predef except the any2stringadd class:

import Predef.{any2stringadd => _, _}

Here's a Scastie.

Upvotes: 7

Related Questions