在 Scala 中使用幻像类型标记原始类型 [英] Marking primitive types with phantom types in Scala
问题描述
在 Scala 中,我可以使用幻像类型的概念(例如 此处) 来标记类型并在运行时删除此信息.我想知道是否可以用幻影类型标记原始类型而不将它们装箱.
In Scala I can use the concept of phantom types (as described e.g. here) to mark types and have this information erased at runtime. I wonder whether it is possible to mark primitive types with phantom types without having them boxed.
一个例子可以是一个函数,它只让 Int 是素数时才通过.签名可能类似于以下内容:
An example could be a function that lets an Int only pass if it is a prime. The signature might look similar to the following:
def filterPrime(i: Int): Option[Int with IsPrime]
函数返回值 Some(i)
如果 i
是质数或 None
否则.
The function returns the value Some(i)
if i
is prime or None
else.
上述想法是否可以在 Scala 中实现而无需对原始整数进行装箱?
Is the stated idea possible to implement in Scala without boxing the primitive integer?
推荐答案
以下对我有用:
trait IsPrime
val x = 5.asInstanceOf[Int with IsPrime]
val y:Int = x
val z:Int with IsPrime = 6 /* this line causes a compile error
which is what you want */
这篇关于在 Scala 中使用幻像类型标记原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!