我正在阅读包含隐式转换的Scala 文档,并决定尝试它:
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)
}如前所述:
要定义自己的隐式转换,必须首先导入
scala.language.implicitConversions(或使用-language:implicitConversions调用编译器)。必须显式启用该功能,因为如果不加区分地使用,它就会有缺陷。
我在IntelliJ和在线IdeOne中都试过了,我没有添加任何特别的东西来使它编译。
它带来了哪些陷阱,为什么没有任何进口就能奏效?
发布于 2016-08-23 12:37:33
你不需要进口任何东西。其思想是,您可以在作用域中的任何地方声明隐式转换函数。例如:
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))
}
}我在这里声明了隐式函数billsToCoins,因此它在main函数的作用域中是可用的。函数作为隐式转换器的唯一需要是拥有implicit修饰符,编译器会找到它并使用它。您可以看到,printCoins函数接受Coins类型的参数,但我能够传递Bills类型的值,并成功地创建了它。以下是控制台输出:
You have 300 coins.
Process finished with exit code 0https://stackoverflow.com/questions/39096089
复制相似问题