0

I'm reading Scala documentation of implicit conversions and decided to try it out:

object Main extends App {
    val test = TestConversion(100)
    test.its
}

class Test[T](val t : T) {
  def its = println(t)
}

object Test {
  def apply[T](t: T): Test[T] = new Test(t)
}

class TestConversion(v : Int) {
  val value = v
}

object TestConversion{
  implicit def implicitConversionTest2Int(ict : TestConversion): Test[Int] = Test(ict.value)
  def apply(v : Int) = new TestConversion(v)
}

As it's said:

To define your own implicit conversions, you must first import scala.language.implicitConversions (or invoke the compiler with -language:implicitConversions). The feature must be explicitly enabled because it has pitfalls if used indiscriminately.

I tried it both in IntelliJ and online IdeOne and I didn't add anything special to make it compile.

What pitfalls it brings and why does it work without any imports?

user3663882
  • 6,957
  • 10
  • 51
  • 92
  • 1
    This is some old stuff that you are reading. You don't have to import anything to use implicit conversions. You might have to add compiler flag, though or else it will give you compile-time *warnings*. – sebszyller Aug 23 '16 at 08:34
  • @sebszyller But what pitfalls do they talk about? – user3663882 Aug 23 '16 at 08:45
  • 1
    When you have many implicits it gets difficult to track them and reason about the code. This is one of the reasons why wildcard imports are so dangerous if not done cautiously. – sebszyller Aug 23 '16 at 08:53
  • 1
    See http://stackoverflow.com/questions/18915114/why-implicitconversions-is-required-for-implicit-defs-but-not-classes. – Alexey Romanov Aug 23 '16 at 08:55

1 Answers1

2

You don't need to import anything. The idea is that you can declare implicit conversion function wherever you want in the scope. For example:

case class Coins(amount:Int)
case class Bills(amount:Int)

object Main {
  implicit def billsToCoins(bills:Bills):Coins = Coins(bills.amount * 100)

  def printCoins(coins:Coins) = println(s"You have ${coins.amount} coins." )

  def main(args:Array[String]): Unit ={
    printCoins(Bills(3))
  }

}

I have declared here implicit function billsToCoins so it is available in scope of the main function. The only thing needed for the function to act as implicit converter is to have the implicit modifier, compiler will find it and use. You see that the printCoins function takes argument of the Coins type but I was able to pass the value of Bills type and it was successfully created. Here is the console output:

You have 300 coins.

Process finished with exit code 0
Alexander Arendar
  • 3,365
  • 2
  • 26
  • 38