gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:48:01 27 4
gpt4 key购买 nike

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

最佳答案

丹尼尔·兰贡(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的无形库中提供的 联合类型来实现。

关于scala - 将Scala类型限制为一组类型之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34906821/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com