Age Mooij
Age Mooij

Reputation: 824

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

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 ?

Upvotes: 7

Views: 1172

Answers (1)

Ken Bloom
Ken Bloom

Reputation: 58780

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.

Upvotes: 6

Related Questions