开发者

How to add object to unparameterized Java List?

开发者 https://www.devze.com 2023-04-08 16:51 出处:网络
I have a Java object OldFashioned that extends Java 1.4 List: [Java] class OldFashioned extends 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 parame开发者_Go百科ters. 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?


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消