deltanovember
deltanovember

Reputation: 44041

In Scala, how can I check if a generic HashMap contains a particular key?

I'm trying to do something like the following

  def defined(hash: HashMap[T, U], key: [T) {
    hash.contains(key)
  }

The above does not compile because my syntax is incorrect. Is it possible to check if a HashMap of unknown type contains a given key?

Upvotes: 1

Views: 8434

Answers (3)

Tom Crockett
Tom Crockett

Reputation: 31579

There's no need to define your own; because all Maps, and all HashMaps in particular, are PartialFunctions, you can use the isDefinedAt method:

scala> val map = HashMap(1->(), 2->())
map: scala.collection.mutable.HashMap[Int,Unit] = Map(1 -> (), 2 -> ())

scala> map.isDefinedAt(2)
res9: Boolean = true

scala> map.isDefinedAt(3)
res10: Boolean = false

Also there is the contains method which is particular to MapLike objects but does the same thing.

Upvotes: 4

Maurício Linhares
Maurício Linhares

Reputation: 40313

Possibly your solution would be something like this:

def detect[K,V]( map : Map[K,V], value : K  ) : Boolean = { 
  map.keySet.contains( value )
}

You declare the generic parameters after the method name and then use them as the types at your parameters.

Upvotes: 1

Rob N
Rob N

Reputation: 16399

Other than the stray "[" I don't think you have a syntax error. That and you need an "=" before your braces, or the function won't be returning the bool. And since there is only one expression, no need for braces...

import scala.collection.mutable._

object Main extends App {

  def defined[T,U](hash: HashMap[T, U], key: T) = hash.contains(key)

  val m = new HashMap[String,Int]
  m.put("one", 1)
  m.put("two", 2)
  println(defined(m, "one"))
  println(m contains "two")
  println(defined(m, "three"))
}

Upvotes: 8

Related Questions