-5

In Scala, how do I declare a Java List that can hold anything?

List[Object] gets upset if I try and put a tuple in it, Scala errors says

type mismatch; found :     java.util.List[Triple[Integer,Integer, Integer]] required: 
java.util.List[Object] Note: Triple[Integer,Integer, Integer] <: Object, but Java-defined 
trait List is invariant in type E. You may wish to investigate a wildcard type 
such as `_ <: Object`. (SLS 3.2.10)

I don't know what this means, how do I declare the list to hold a triple (or a tuple, or anything)

My code looks like this (it is twirl, so it has @, but it is just Scala code):

@import java.util.List;

@(field:List[Object], min:Int=1)(f: Object, Int) => Html)
@{
    (0 until math.max(if (field.isEmpty) 0 else field.size, min))
        .map(i => f(field.get(i),i))
}
SergGr
  • 23,570
  • 2
  • 30
  • 51
bharal
  • 15,461
  • 36
  • 117
  • 195

1 Answers1

0

Use a Scala (not Java) collection, e.g. scala.collection.Seq[Any]. If it needs to be mutable, look at scala.collection.mutable

scala> val t = Tuple3[Int,Int,Int](1,2,3)
t: (Int, Int, Int) = (1,2,3)

scala> val listAny: Seq[Any] = Seq[Any](t,t,5,"happy now?")
listAny: Seq[Any] = List((1,2,3), (1,2,3), 5, happy now?)

If you insist on using Java collections, you can try field:List[_ <: Object], as suggested by the error message. Also note that you can pass Scala collections to a Java app, because at runtime the Scala code is represented by compiled bytecode that is compatible with the JVM.

radumanolescu
  • 4,059
  • 2
  • 31
  • 44
  • um, i don't want to do that bc i'm using play framework with Java, so sending in a Java List - also you're not really answering the question! – bharal Mar 17 '17 at 21:29
  • 2
    Sorry - confused by "In Scala, how do i declare a list that holds anything". I thought you needed a list that holds anything, in Scala – radumanolescu Mar 17 '17 at 21:37