Reputation: 7367
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?
Upvotes: 0
Views: 97
Reputation: 3435
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
Upvotes: 2