【问题标题】:Restrict Scala type to be one of a set of types将 Scala 类型限制为一组类型之一
【发布时间】:2016-01-20 17:37:39
【问题描述】:

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

【问题讨论】:

  • 听起来像类型类会更适合你,但用例是什么?
  • 简单的事情可能是拥有f[T <: AnyVal],这很接近。否则,我担心您将不得不使用您的选项创建一个密封特征:stackoverflow.com/questions/3790980/…

标签: scala generics


【解决方案1】:

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 的 联合类型 来实现,正如他的无形库中提供的那样。

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 2019-05-10
    • 2010-09-27
    相关资源
    最近更新 更多