The redesign of contextual abstractions brings some incompatibilities.
Incompatibility | Scala 2.13 | Scala 3 Migration Rewrite | Scalafix Rule | Runtime Incompatibiltiy |
---|---|---|---|---|
Type of implicit def | ✅ | |||
Implicit views | Possible | |||
View bounds | Deprecation | |||
Ambiguous conversion on A and => A |
Type Of Implicit Definition
The type of implicit definitions (val
or def
) needs to be given explicitly in Scala 3.
They cannot be inferred anymore.
The Scalafix rule named ExplicitResultTypes can write the missing type annotations automatically.
Implicit Views
Scala 3 does not support implicit conversion from an implicit function value, of the form implicit val ev: A => B
.
The following piece of code is now invalid in Scala 3:
trait Pretty {
val print: String
}
def pretty[A](a: A)(implicit ev: A => Pretty): String =
a.print // In Scala 3, Error: value print is not a member of A
The Scala 3 migration compilation can warn you about those cases, but it does not try to fix it.
Be aware that this incompatibility can produce a runtime incompatibility and break your program. Indeed the compiler can find another implicit conversion from a broader scope, which would eventually cause an undesired behavior at runtime.
The resolved conversion depends on the compiler mode:
-source:3.0-migration
: the compiler performs theev
conversion-source:3.0
: the compiler cannot perform theev
conversion but it can perform theanyPretty
, which is undesired
In Scala 3, one simple fix is to supply the right conversion explicitly:
View Bounds
View bounds have been deprecated for a long time but they are still supported in Scala 2.13. They cannot be compiled with Scala 3 anymore.
def foo[A <% Long](a: A): Long = a
In this example, in Scala 3, we get this following error message:
The message suggests to use a context bound instead of a view bound but it would change the signature of the method. It is probably easier and safer to preserve the binary compatibility. To do so the implicit conversion must be declared and called explicitly.
Be careful not to fall in the runtime incompatibility described above, in Implicit Views.
Ambiguous Conversion On A
And => A
In Scala 2.13 the implicit conversion on A
wins over the implicit conversion on => A
.
It is not the case in Scala 3 anymore, and leads to an ambiguous conversion.
For instance, in this example:
implicit def boolFoo(bool: Boolean): Foo = ???
implicit def lazyBoolFoo(lazyBool: => Boolean): Foo = ???
true.foo()
The Scala 2.13 compiler chooses the boolFoo
conversion but the Scala 3 compiler fails to compile.
A temporary solution is to write the conversion explicitly.