简体   繁体   中英

Scala's HashSet doesn't seem to implement Set?

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.

  1. Mutable collection (Read and write)

    scala.collection.mutable.*

  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM