Daniel Landgon 的上述评论指出了正确的方向。
如果有人急于点击链接:
@annotation.implicitNotFound("It can not be proven that ${T} is of type Int, Long, Float or Double")
sealed trait Foo[T]
object Foo {
implicit val intFoo: Foo[Int] = new Foo[Int]{}
implicit val LongFoo: Foo[Long] = new Foo[Long]{}
implicit val FloatFoo: Foo[Float] = new Foo[Float]{}
implicit val DoubleFoo: Foo[Double] = new Foo[Double]{}
}
与:
def bar[T](t: T)(implicit ev: Foo[T]): Unit = println(t)
我们得到:
bar(5) // res: 5
bar(5.5) // res: 5.5
bar(1.2345F) // res: 1.2345
bar("baz") // Does not compile. Error: "It can not be proven that String is of type Int, Long, Float or Double"
bar(true) // Does not compile. Error: "It can not be proven that Boolean is of type Int, Long, Float or Double"
这也可以通过 Miles Sabin 的 联合类型 来实现,正如他的无形库中提供的那样。