第一个问题是由于您在 REPL 中的工作方式,第二个问题是foobar
只是掩盖了第一个。如果您想要重载定义,则需要使用:paste
同时定义两者。
这仍然不会让你得到你想要的,只是一个新的错误消息:
scala> println(foobar(new Foo))
<console>:14: error: ambiguous reference to overloaded definition,
both method foobar of type [T](x: T)(implicit ev: EGT.<:!<[T,Foo])Int
and method foobar of type [T](x: T)(implicit ev: <:<[T,Foo])String
match argument types (Foo) and expected result type Any
println(foobar(new Foo))
^
(注意我已经缩写了ExtendedGenericTypes
因为我讨厌水平滚动条。)
您甚至可以尝试提供<:<
明确实例:
scala> foobar(new Foo)(implicitly[Foo <:< Foo])
<console>:14: error: ambiguous reference to overloaded definition,
both method foobar of type [T](x: T)(implicit ev: EGT.<:!<[T,Foo])Int
and method foobar of type [T](x: T)(implicit ev: <:<[T,Foo])String
match argument types (Foo)
foobar(new Foo)(implicitly[Foo <:< Foo])
^
所以这里发生的事情是编译器不会让第二个参数列表确定要使用哪个重载定义。这似乎意味着具有多个参数列表且第一个参数列表相同的重载方法本质上是无用的。可能有一张票——乍一看我能想到的最接近的是SI-2383.
不过,这些都不重要,因为您不应该在这里使用重载方法——重载是一个可怕的“功能”,是 Java 和 Java 的后遗症。破坏各种东西.
不过,还有其他可能的方法。我最喜欢的一些奇怪的 Scala 技巧依赖于这样一个事实:您可以为隐式参数提供默认值,如果编译器找不到实例,将使用该默认值。如果我理解正确的话,你想要这样的东西:
class Foo
def foobar[T](x: T)(implicit ev: T <:< Foo = null) =
Option(ev).fold[Either[Int, String]](Left(5))(_ => Right("hello"))
case class Bar(i: Int) extends Foo
case class Baz(i: Int)
进而:
scala> foobar(Bar(13))
res0: Either[Int,String] = Right(hello)
scala> foobar(Baz(13))
res1: Either[Int,String] = Left(5)
请注意,我正在使用Either
而不是让隐式的存在决定返回类型。有一些方法可以实现这一点(比如无形的's 第一类多态函数值),但在这种情况下他们可能有点矫枉过正了。
更新:好的,既然你要求了:
import shapeless._
trait LowPriorityFoobar { this: Poly1 =>
implicit def anyOld[T] = at[T](_ => 5)
}
object foobar extends Poly1 with LowPriorityFoobar {
implicit def foo[T](implicit ev: T <:< Foo) = at[T](_ => "hello")
}
进而:
scala> foobar(Bar(13))
res6: String = hello
scala> foobar(Baz(13))
res7: Int = 5
没有包装纸。不过,在采取这种方法之前,您应该认真考虑一下。
更新到更新,为了完整性:您也可以更直接地(但也更详细地)执行此操作,而无需使用依赖方法类型的 Shapeless(同样,您需要使用:paste
一次定义所有这些):
class Foo
trait IsFooMapper[I] {
type Out
def apply(i: I): Out
}
trait LowPriorityIsFooMapper {
implicit def isntFoo[A] = new IsFooMapper[A] {
type Out = Int
def apply(a: A) = 5
}
}
object IsFooMapper extends LowPriorityIsFooMapper {
implicit def isFoo[A](implicit ev: A <:< Foo) = new IsFooMapper[A] {
type Out = String
def apply(a: A) = "hello"
}
}
def foobar[A](a: A)(implicit ifm: IsFooMapper[A]) = ifm(a)
进而:
scala> foobar(Bar(13))
res0: String = hello
scala> foobar(Baz(13))
res1: Int = 5
再次强调,这是相当高级的东西,应该谨慎使用。