How to convert an untyped java.util.List to a Scala 2.8 Buffer
Asked Answered
K

1

7

I have to call some Java library code that returns an untyped java.util.List and I can't seem to convert this into a Scala 2.8 list without the compiler borking with the following error:

[INFO]  found   : java.util.List[?0] where type ?0
[INFO]  required: java.util.List[AnyRef]
[INFO]      val modules: Buffer[AnyRef] = asScalaBuffer(feedEntry.getModules)

I've tried both the normal

import scala.collection.JavaConversions._

val modules: Buffer[AnyRef] = feedEntry.getModules

as the explicit

val modules: Buffer[AnyRef] = asScalaBuffer(feedEntry.getModules)

I know the type of the items in the list and I've tried setting that as the type of the Buffer but I keep getting the same error.

I've looked around but all the documentation assumes the Java list to be typed. How do I convert untyped lists ?

Knighthood answered 7/1, 2011 at 17:40 Comment(0)
C
6

I think you'll just have to cast it to the right type.

val modules: Buffer[AnyRef] = 
  feedEntry.getModules.asInstanceOf[java.util.List[AnyRef]]

Scala can take it from there and apply the implicit conversion from JavaConversions to wrap it as a Scala collection.

Coronach answered 7/1, 2011 at 17:55 Comment(2)
And casting to the type of the actual items in the list also works without a problem.Knighthood
@Age, yes it does. I just assumed that since you were trying to cast to AnyRef, that's what you really wanted in the end. (For example, if you were working with JDOM.)Coronach

© 2022 - 2024 — McMap. All rights reserved.