top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is Option in Scala?

+2 votes
288 views

What are Some and None? What is Option/Some/None Design Pattern in Scala?

posted Jun 28, 2016 by Roshan

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes
 
Best answer

In Scala, Option is used to represent optional values that is either exist or not exist and Option is an abstract class. Option has two subclasses:
1.Some and
2.None.
All three (Option, Some and None) are defined in “scala” package like “scala.Option”.Option is a bounded collection in Scala,which contains either zero or one element. If Option contains zero elements that is None. If Option contains one element, that is Some.
Some is used to represent existing value. None is used to represent non-existent value.Example:-

def get(val index: Int): Option[String]

Let us assume that this method is from List. This method has a return type of Option[String]. If List contains elements, this get method returns “Some[String]” element available in that index position. Otherwise, it returns “None” (that is no elements)Some is a case class and None is an Object. As both are case class/object, we can use them in Pattern Matching very well.The combination of all these three definitions is known as Option/Some/None Design Pattern in Scala.

answer Jun 28, 2016 by Shivam Kumar Pandey
Similar Questions
+4 votes

What is the main use of Option and Either in Scala? How do we handle Errors or Exceptions in Functional Style(FP style) in Scala?

0 votes

What is the equivalent construct of Scala’s Option in Java SE 8? What is the use of Option in Scala?

...