2

How can I make that conversion?

var attrDefs = Vector(new AttributeDefinition(), new AttributeDefinition());

request.setAttributeDefinitions(attrDefs);

I've read in many different places that we should just import this:

import scala.collection.JavaConverters._

And it should work, but it doesn't compile.

I'm getting this error:

 found   : scala.collection.immutable.Vector[AttributeDefinition][scalac]
 required: java.util.Collection[AttributeDefinition]

I'm using Scala 2.9.3.

Community
  • 1
  • 1
Cacho Santa
  • 6,846
  • 6
  • 41
  • 73

2 Answers2

2

You need to call asJavaCollection to do the conversion, this should work:

import scala.collection.JavaConverters._

var attrDefs = Vector(new AttributeDefinition(), new AttributeDefinition())

request.setAttributeDefinitions(attrDefs.asJavaCollection)

As an alternative, you can use import scala.collection.JavaConversions._ to not have to call asJavaCollection. However, I find that it makes what the code is doing more readable to call the method. Here's the alternate example:

import scala.collection.JavaConversions._

var attrDefs = Vector(new AttributeDefinition(), new AttributeDefinition())

request.setAttributeDefinitions(attrDefs)
Noah
  • 13,821
  • 4
  • 36
  • 45
  • awesome @Noah! I'm having so many issues with my Scala plugin for Eclipse. Actually, it is still showing me that the method does not exist, but it works! – Cacho Santa Jul 19 '13 at 01:25
  • 1
    I'm not sure how attached you are to Eclipse but I find that Intellij is far better at most things, including Scala :) – Noah Jul 19 '13 at 01:26
  • A lot of people in my team are using Intellij already, I think Scala will force me to migrate :O) – Cacho Santa Jul 19 '13 at 01:29
1

As of Scala 2.9, you should prefer covert package for converting Java <-> Scala collections:

val attr = new java.util.Vector[String]()
scala.collection.convert.wrapAsScala.collectionAsScalaIterable(attr) // it's implicit

so import wrapAsScala:

import collection.convert.wrapAsScala._
var attrDefs = Vector(new AttributeDefinition(), new AttributeDefinition())
request.setAttributeDefinitions(attrDefs)
4lex1v
  • 21,367
  • 6
  • 52
  • 86