Below is my HashMap:
val params1 = collection.mutable.HashMap[String, Any]()
params1 += "forCourseId" -> "2"
println(params1.isDefinedAt("forCourseId"))
println(params1.contains("forCourseId"))
What is difference between isDefinedAt() & contains() method?
I need to check whether key is present or not main concern is , it will not throw null pointer exception.
You can check the Scala source code. In MapLike.scala you'll see that isDefinedAt is actually just calling contains, meaning that they are truly identical:
def isDefinedAt(key: A) = contains(key)
The only real difference is that contains is specific to the Map interface (specifically it's declared on GenMapLike), while isDefinedAt is found on all PartialFunction classes.
val m: Map[Int,Int] = Map(1 -> 2)
val pf: PartialFunction[Int,Int] = { case 1 => 1 }
m.isDefinedAt(1) // ok
m.contains(1) // ok
pf.isDefinedAt(1) // ok
pf.contains(1) // doesn't compile
According to the Scala Doc isDefinedAt is equivalent to contains.
This method, which implements an abstract method of trait PartialFunction, is equivalent to contains.
http://www.scala-lang.org/api/current/#scala.collection.mutable.HashMap
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With