0

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.