Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add object to unparameterized Java List?

I have a Java object OldFashioned that extends Java 1.4 List:

[Java] 
class OldFashioned extends List { ... }

That is, OldFashioned doesn't take any type parameters. I need to add SomeObject to it. In Java there's no problem, since it treats List 1.4 as List<Object> 1.5 and allows to add any subclasses of Object to the collection. But Scala doesn't. So next code doesn't work:

[Scala]
val oldFashioned = new OldFashioned()
oldFashioned.add(new SomeObject)       // found: SomeObject; required: E

That is, Scala compiler requires to pass type parameters to OldFashioned that actually doesn't take them:

[Scala]
var oldFashioned: OldFashioned[SomeObject] = null    // OldFashioned does not take type parameters

How can I overcome it and add SomeObject to OldFashined?

like image 622
ffriend Avatar asked Sep 28 '11 00:09

ffriend


1 Answers

Ok, I can't believe one of my earlier question finds a usage here (you should go upvote agilesteel's answer)

def add(oldFashioned: OldFashioned, any: Any): Boolean = oldFashioned match {
  case l: java.util.List[a] => l.add(any.asInstanceOf[a])
}

val oldFashioned = new OldFashioned
// oldFashioned: OldFashioned = []

add(oldFashioned, "test")
// res0: Boolean = true
add(oldFashioned, 1)
// res1: Boolean = true
add(oldFashioned, new Object)
// res2: Boolean = true

oldFashioned
// res3: OldFashioned = [test, 1, java.lang.Object@1db8f8e]

Edit: I guess as long as I'm going to cast:

oldFashioned.asInstanceOf[java.util.List[SomeObject]].add(new SomeObject)
like image 194
huynhjl Avatar answered Nov 18 '22 18:11

huynhjl