Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

type conversion - Convert Scala Set into Java (java.util.Set)?

I have a Set in Scala (I can choose any implementation as I am creating the Set. The Java library I am using is expecting a java.util.Set[String].

Is the following the correct way to do this in Scala (using scala.collection.jcl.HashSet#underlying):

import com.javalibrary.Animals

var classes = new scala.collection.jcl.HashSet[String]
classes += "Amphibian"
classes += "Reptile"
Animals.find(classes.underlying)

It seems to be working, but since I am very new to Scala I want to know if this is the preferred way (any other way I try I am getting a type-mismatch error):

error: type mismatch;
 found   : scala.collection.jcl.HashSet[String]
 required: java.util.Set[_]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you were asking about Scala 2.8, Java collections interoperability is supplied by scala.collection.JavaConversions. In this case, you want JavaConversions.asSet(...) (there's one for each direction, Java -> Scala and Scala -> Java).

For Scala 2.7, each scala.collection.jcl class that wraps a Java collection has an underlying property which provides the wrapped Java collection instance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...