In Scala Option, what is the difference between its isDefined and nonEmpty method? Is there any performance difference between the two?
Definition Classes IterableOps. final def isDefined: Boolean. Returns true if the option is an instance of scala. Some, false otherwise. Returns true if the option is an instance of scala.Some, false otherwise.
Scala Option[ T ] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value.
Scala some class returns some value if the object is not null, it is the child class of option. Basically, the option is a data structure which means it can return some value or None. The option has two cases with it, None and Some. We can use this with the collection.
The nonEmpty function is applicable to both Scala's Mutable and Immutable collection data structures. The nonEmpty method will test whether a given collection is not empty and will return either true or false As per the Scala documentation, the definition of the nonEmpty method is as follows:
Scala | Option Last Updated : 01 Apr, 2019 The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null.
The nonEmpty method will test whether a given collection is not empty and will return either true or false As per the Scala documentation, the definition of the nonEmpty method is as follows: The nonEmpty method is a member of the TraversableOnce trait, but there are other concrete implementations for corresponding collection types.
If Option didn't provide nonEmpty, it would be provided through the conversion to an Iterable, which invokes toList. Do you want to turn your Option into a List just to check that property? Of course not. So the issue is not whether nonEmpty is more efficient vis-a-vis isDefined, but vis-a-vis the conversion.
Looking at the source, the definition of nonEmpty
is:
final def nonEmpty = isDefined
From Scala 2.13.x codebase, it's:
def isDefined: Boolean = !isEmpty ... final def nonEmpty = isDefined
So, logically, no difference between the two.
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