第一个问题是,由于您在 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 和 breaks all kinds of stuff 的遗留问题。
不过,还有其他可能的方法。我最喜欢的一些奇怪的 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,而不是让隐式的存在确定返回类型。有一些方法可以做到这一点(比如Shapeless 的first-class polymorphic function values),但在这种情况下它们可能有点矫枉过正。
更新:好的,既然你要求它:
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
同样,这是相当高级的东西,应谨慎使用。