0
很长一段时间我都试图避免隐式类,但最近我陷入了它。目前我无法弄清楚为什么我的函数aFunc2
的返回类型无法转换为其隐式形式,因为它为aFunc1
中的参数所做的操作。如何使用隐式类作为函数结果类型
object SO extends App {
implicit class Experiment[K, V](tpl: (K, V))(implicit o: Ordering[K], f: Fractional[V]) {
def foo(): String = "Bar"
}
// Works
println((12, 23.1).foo())
// Works
def aFunc1[K, V](e: Experiment[K, V]): String = e.toString
println(aFunc1((12, 23.1)))
// does not - why ?
def aFunc2[K, V](e: Experiment[K, V]): Experiment[K, V] = (12, 23.1)
}
编辑1:其实这有做的类型,所以让我扩展示例一点点:
object SO extends App {
implicit class Experiment[K, V](tpl: (K, V))(implicit o: Ordering[K], f: Fractional[V]) {
def foo(): (K, V) = (tpl._1, tpl._2)
}
// Works
println((12, 23.1).foo())
// Works
def aFunc1[K, V](e: Experiment[K, V]): String = e.toString
println(aFunc1((12, 23.1)))
// still does not but K and V should actually match - i guess
def aFunc2[K, V](e: Experiment[K, V]): Experiment[K, V] = e.foo()
}
错误:
Error:(19, 66) type mismatch;
found : (K, V)
required: scratch.SO.Experiment[K,V]
def aFunc2[K, V](e: Experiment[K, V]): Experiment[K, V] = e.foo()
是的,这是真的,它与类型有关,所以我稍微扩展了我的问题。 – KIC
@KIC我已添加更新,您可以试试吗?我不得不承认,因为我现在没有正式的scala发布版本,所以我在这里瞎了眼。 –
辉煌的作品 - thx! – KIC