David Tavan
David Tavan

Reputation: 69

Generic lists in scala

As I was working with Java I was able to create generic lists with constraints, covariant, Contravariant etc..

List<? extends Chat> chats=new ArrayList<Siamois>(); ...

But know I have to work in Scala I used constraints for methods and for class for instance :

def addToList[T <: Chat](t:T):List[T]=List[T](t)

but in fact is there a way to write these lines of java in Scala ?

 List<? extends Chat> chats=new ArrayList<Siamois>();
List<? super Siamois> siamois2=new ArrayList<Chat>();

thanks

Upvotes: 0

Views: 439

Answers (1)

Jasper-M
Jasper-M

Reputation: 15086

The literal translation would be

import java.util.{List, ArrayList}

val chats: List[_ <: Chat] = new ArrayList[Siamois]
val siamois2: List[_ >: Siamois] = new ArrayList[Chat]

But note that the immutable List from the Scala standard library is covariant by definition. In idiomatic Scala code you won't need use-site variance. You'll probably want to read up on Scala's declaration-site variance.

Upvotes: 3

Related Questions