将Scala类型限制为一组类型之一

use*_*206 7 generics scala

有没有办法定义一个泛型类型参数,它可以是一小组类型之一?我想定义一个类型T,它只能是{Int,Long,Float,Double}之一.

Car*_*ira 5

丹尼尔·兰德贡的上述评论指出了正确的方向。
如果有人急于点击链接:

@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]{}
}
Run Code Online (Sandbox Code Playgroud)

和:

def bar[T](t: T)(implicit ev: Foo[T]): Unit = println(t)
Run Code Online (Sandbox Code Playgroud)

我们得到:

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"
Run Code Online (Sandbox Code Playgroud)

这也可以通过 Miles Sabin 的无形库中提供的联合类型来实现。