将Scala类型限制为一组类型之一
发布时间:2020-12-16 18:31:23 所属栏目:安全 来源:网络整理
导读:有没有办法定义一个泛型类型参数,它可以是一小组类型之一?我想定义一个类型T,它只能是{Int,Long,Float,Double}之一. 解决方法 Daniel Landgon的评论指出了正确的方向. 万一有人急于点击链接: @annotation.implicitNotFound("It can not be proven that ${T
有没有办法定义一个泛型类型参数,它可以是一小组类型之一?我想定义一个类型T,它只能是{Int,Long,Float,Double}之一.
解决方法
Daniel Landgon的评论指出了正确的方向.
万一有人急于点击链接: @annotation.implicitNotFound("It can not be proven that ${T} is of type Int,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,Float or Double" bar(true) // Does not compile. Error: "It can not be proven that Boolean is of type Int,Float or Double" 这也可以通过他的无形库中提供的Miles Sabin的联合类型来实现. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |