Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Scala Option's isDefined and nonEmpty method

Tags:

scala

In Scala Option, what is the difference between its isDefined and nonEmpty method? Is there any performance difference between the two?

like image 844
WoLfPwNeR Avatar asked Mar 21 '14 22:03

WoLfPwNeR


People also ask

What is isDefined in Scala?

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.

What is option type in Scala?

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.

What is some in Scala?

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.

What is the use of nonempty in Scala?

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:

What is option in Scala?

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.

How to test if a collection is not empty in Scala?

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.

Is nonempty more efficient than isdefined?

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.


2 Answers

Looking at the source, the definition of nonEmpty is:

final def nonEmpty = isDefined

like image 187
Lee Avatar answered Sep 28 '22 10:09

Lee


From Scala 2.13.x codebase, it's:

def isDefined: Boolean = !isEmpty ... final def nonEmpty = isDefined 

So, logically, no difference between the two.

like image 40
Johnny Avatar answered Sep 28 '22 11:09

Johnny