Reputation: 44041
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
Reputation: 31579
There's no need to define your own; because all Map
s, and all HashMap
s in particular, are PartialFunction
s, 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
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
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