find method in scala's collection

978 Views Asked by At

Per the documentation, find function in scala's collection wraps the resulting elements in Option object. In the below, the size operation ends in error; where as the endsWith produces correct result.

The second element in the list being null, both should error out / produce correct result.

val a1:String = "ABCDEF"
val a2:String = null
val res12 = List(ABCDEF, null)

res12 filter { _.size > 10 }              //errors out
java.lang.NullPointerException
  at scala.collection.immutable.StringOps$.length$extension(StringOps.scala:51)
  at scala.collection.immutable.StringOps.length(StringOps.scala:51)
  at scala.collection.SeqLike.size(SeqLike.scala:108)
  at scala.collection.SeqLike.size$(SeqLike.scala:108)
  at scala.collection.immutable.StringOps.size(StringOps.scala:33)
  at .$anonfun$res19$1(<console>:13)
  at .$anonfun$res19$1$adapted(<console>:13)
  at scala.collection.TraversableLike.$anonfun$filterImpl$1(TraversableLike.scala:251)
  at scala.collection.immutable.List.foreach(List.scala:392)
  at scala.collection.TraversableLike.filterImpl(TraversableLike.scala:250)
  at scala.collection.TraversableLike.filterImpl$(TraversableLike.scala:248)
  at scala.collection.AbstractTraversable.filterImpl(Traversable.scala:108)
  at scala.collection.TraversableLike.filter(TraversableLike.scala:262)
  at scala.collection.TraversableLike.filter$(TraversableLike.scala:262)
  at scala.collection.AbstractTraversable.filter(Traversable.scala:108)
  ... 28 elided

res12 find { _.endsWith("EF") }       //produces correct result
res20: Option[String] = Some(ABCDEF)
2

There are 2 best solutions below

8
jwvh On BEST ANSWER

both should error out / produce correct result

No they shouldn't.

filter() has to touch every element to see if it's in or out. If there's a bomb in the collection then it will be detonated.

find() is lazy. Find the 1st element to pass the predicate test and we're outa here. One and done.

0
Brian On

This produces an error because you are calling size on a null String which is in fact a NullPointerException

scala> val s: String = null
val s: String = null

scala> s.size
java.lang.NullPointerException
  at scala.collection.StringOps$.size$extension(StringOps.scala:165)
  ... 32 elided