5

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?

ffriend
  • 27,562
  • 13
  • 91
  • 132

1 Answers1

8

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)
Community
  • 1
  • 1
huynhjl
  • 41,520
  • 14
  • 105
  • 158
  • Funnily, IDEA highlights `[a]` as an error, but Scala compiler doesn't complaint, so it works. Upvotes for both your and agilesteel's answers. Thanks! – ffriend Sep 28 '11 at 12:36
  • I already started to wonder, why one of my old answers was getting a few upvotes all of a sudden ;) Thanks right back at you! – agilesteel Sep 28 '11 at 13:38