Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I setup multiple type bounds in Scala?

Tags:

generics

scala

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?

like image 792
oxbow_lakes Avatar asked Sep 29 '09 08:09

oxbow_lakes


People also ask

What are Type bounds?

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.

What is type parameter in Scala?

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.


1 Answers

Use Compound Type:

trait Narrowable[A] extends Iterable[A] {
  def narrow[B <: A with AnyRef] : Iterable[B]
}
like image 198
Walter Chang Avatar answered Oct 16 '22 18:10

Walter Chang