我正在定义一些 Scala 隐式,以便更轻松地使用一组特定的不可更改的 Java 类。以下 Scala 代码是一个简化的示例,显然看起来很疯狂,在现实世界中,我试图从 Monkey、Tree 和 Duck 中隐式获取特定资源(而不是数字年龄),以用于各种方法,例如purchaseCandles()
:
// actually 3 Java classes I can not change:
case class Monkey(bananas: Int)
case class Tree(rings: Int)
case class Duck(quacks: Seq[String])
// implicits I created to make my life easier...
implicit def monkey2Age(monkey: Monkey): Int = monkey.bananas / 1000
implicit def tree2Age(tree: Tree): Int = tree.rings
implicit def duck2Age(duck: Duck): Int = duck.quacks.size / 100000
// one of several helper methods that I would like to define only once,
// only useful if they can use an implicit parameter.
def purchaseCandles()(implicit age: Int) = {
println(s"I'm going to buy $age candles!")
}
// examples of usage
{
implicit val guest = Monkey(10000)
purchaseCandles()
}
{
implicit val guest = Tree(50)
purchaseCandles()
}
{
implicit val guest = Duck(Seq("quack", "quack", "quack"))
purchaseCandles()
}
编译器错误,发生 3 次:
could not find implicit value for parameter age: Int
purchaseCandles()
^
抛开这个示例代码疯狂的许多不同方式,我真正的问题是:隐式值的隐式转换能否满足 Scala 中的隐式参数?