VOOZH about

URL: https://www.geeksforgeeks.org/scala/scala-methods-to-call-option/

⇱ Scala | Methods to Call Option - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Scala | Methods to Call Option

Last Updated : 11 Jul, 2025
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. There are a few methods that we can Call on Scala Option.
  • def get: A This method is utilized to return an Option's value. Example:
    Output:
    20
    
    Here, get method cannot be applied to the None class as it will show an exception.
  • def productArity: Int This method is utilized to return the size of the Option's value. Example:
    Output:
    1
    
  • def productElement(n: Int): Any This method is utilized to return the n-th element of the stated product and here indexing starts from zero. Example:
    Output:
    20
    
    Here, None will show an exception.
  • def exists(p: (A) => Boolean): Boolean When the value of the Option satisfies the stated condition then, this method returns true else returns false. Example:
    Output:
    true
    
    Here, the condition stated is satisfied so, true is returned.
  • def filter(p: (A) => Boolean): Option[A] This method is utilized to return the value of the Option if the stated condition is satisfied. Example:
    Output:
    Some(30)
    
    Here, the condition is satisfied so, the Option value is returned and returns None if the predicate is not satisfied.
  • def filterNot(p: (A) => Boolean): Option[A] This method will return the Option value if the stated condition is not satisfied. Example:
    Output:
    Some(30)
    
    Here, the condition is not satisfied so, the Option value is returned and returns None if the predicate is satisfied.
  • def isDefined: Boolean This method returns true if the Option is an instance of Some and returns false if the Option is an instance of None. Example:
    Output:
    true
    false
    
  • def iterator: Iterator[A] This method returns an iterator on the Option given. Example:
    Output:
    non-empty iterator
    
  • def map[B](f: (A) => B): Option[B] This method will return the value of the function stated in the Map, if the Option has a value. Example:
    Output:
    Some(60)
    
    These were the methods to call on an Option and there are more such methods.
  • def orElse[B >: A](alternative: => Option[B]): Option[B] If the Option contain a value, this returns it. Otherwise, this method evaluates the alternative and returns alternative.  
  • def orNull This method will return Null, if the Option didn't contain a value.
Comment
Article Tags:

Explore