Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala map isDefinedAt() vs contains() method

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.

like image 431
Swadeshi Avatar asked Mar 08 '16 07:03

Swadeshi


2 Answers

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
like image 70
dhg Avatar answered Nov 15 '22 06:11

dhg


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

like image 2
Brian Avatar answered Nov 15 '22 05:11

Brian