Why does implicit def require importing implicitConversions, but implicit val does not?

I read this tutorial and below it points

Since implicit conversions can have errors if they are used indiscriminately, the compiler warns when compiling an implicit transform definition. To turn off warnings, do one of the following: Import scala.language.implicitConversions into the scope of the implicit conversion ...

A warning does not occur if you use implicit val rather than implicit def. Why is this?

In other words, if I do the following, I do not need import:

implicit val int2str = (i: Int) => i.toString

But if I do the following, I need an import:

implicit def int2str(i: Int) = i.toString

----- ----- updated Here is a toy example showing that the implicit val works:

case class CoolString(coolString: String)

class RichCoolString(rich: CoolString) {
  val hasCat: Boolean = rich.coolString.contains("cat")
}

object RichCoolString {
  implicit val coolStringToRichCoolString = (coolString: CoolString) => new 
RichCoolString(coolString)
}

scala> import RichCoolString._
import RichCoolString._

scala> CoolString("cool cats").hasCat
res0: Boolean = true
+4

Source: https://habr.com/ru/post/1680169/


All Articles