In Java we can apply only AND restriction to type bound like this:
public class <T extends Serializable & SomeThingDoable> MyClass{
//...
}
But we could not tell Java to hold OR restriction.
Is it possible in Scala to provide a restrictions that it would be possible to add an element into a collection iff it's of type SomeType1
OR SomeType2
You can't really do that with guaranteeing type safety.
I mean, you could just do an instance
and throw an error when the class is instantiated, but that's pretty dirty.
The much better solution is to use ADT (Abstract Data Types):
sealed trait NaturalNumber
final case class Zero() extends NaturalNumber
final case class Next(i: NaturalNumber) extends NaturalNumber
object Main extends App {
val a: NaturalNumber = Next(Zero())
a match {
case Zero() => "zero"
}
}
Which gives exhaustivity checking:
<console>:16: warning: match may not be exhaustive.
I'd suggest using something like coproducts
Also note that Dotty will have AND/OR built-in restrictions on types.
there is no language level construct that supports this exactly, but as @dveim points out, i believe this is coming soon.
if you are asking with a specific practical use case in mind, you do have a few options though. you could use Either[SomeType1, SomeType2]
, which has all of the constructs you need to represent this idea (but is not a type bound).
alternatively, you can achieve this effect using typeclasses:
sealed trait Or[T] {
def someMethod(t: T): String
}
object Or {
implicit object OrInt extends Or[Int] {
def someMethod(t: Int): String = "int"
}
implicit object OrLong extends Or[Long] {
def someMethod(t: Long): String = "long"
}
}
object Test {
import Or._
def test[T](value: T)(implicit or: Or[T]): String =
or.someMethod(value)
}
please excuse the trivial example, but what you get here is:
sealed trait
which means, you can restrict others from adding more instances to the Or
family (unless they can edit the actual file it's defined in)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.