I have a Scala class:
class Example {
def fooBar() : String = {
// do some stuff
var whistles = new HashSet[String]()
fizzBuzz(whistles)
// do some more stuff
}
def fizzBuzz(whistles : Set[String]) : Unit = {
// do some stuff down here
}
}
This gives me compiler errors when I call the fizzBuzz
method (from inside fooBar
), stating:
type mismatch; found : java.util.HashSet[String] required: Set[String]
What am I missing here?!? HashSet
implements Set
, the last time I checked...
You're mixing java.util.HashSet[A]
, the java version of HashSet
, with scala.collection.immutable.Set[A]
. You want scala.collection.immutable.HashSet[A]
instead:
val whistles = scala.collection.immutable.HashSet[String]()
fizzBuzz(whistles)
Scala has neat implementation of collections.It has two flavor of collection.
Mutable collection (Read and write)
scala.collection.mutable.*
Immutable collection (read-only)
scala.collection.immutable.*
you should not confuse between two variants.
Mutable
val mutableHashset = scala.collection.mutable.HashSet[String]()
mutableHashset += "name"
mutableHashset.foreach { println }
Immutable
val immutableHashSet = scala.collection.immutable.HashSet[String]("Name", "Age", "Address")
immutableHashSet.foreach { println }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.