I want to be able to declare something like this:
trait Narrowable[A] extends Iterable[A] {
def narrow[B <: A & B <: AnyRef] : Iterable[B]
}
That it, the type B
should be both a subtype of A
and AnyRef
. Is this possible?
In Scala, Type Bounds are restrictions on Type Parameters or Type Variable. By using Type Bounds, we can define the limits of a Type Variable. Scala Type Bounds give us the benefit of Type-Safe Application Development. Scala supports the following Type Bounds for Type Variables: Scala Upper Bounds.
Language. Methods in Scala can be parameterized by type as well as value. The syntax is similar to that of generic classes. Type parameters are enclosed in square brackets, while value parameters are enclosed in parentheses.
Use Compound Type:
trait Narrowable[A] extends Iterable[A] {
def narrow[B <: A with AnyRef] : Iterable[B]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With