Home »
Scala
How to convert a list to option in Scala?
Scala | Convert a list to option: In this article, we will learn the conversion of a list to option in Scala.
Submitted by Shivang Yadav, on June 13, 2020
In programming, there might be cases when the programmer needs to keep a check on data structure so that only non-empty collection can be processed to avoid errors and exceptions in the code. One such case can be when the program contains a list that can be empty, hence we have to convert the empty list to none by converting the list to option.
This option will give the list if not empty otherwise will return none.
List in Scala is a collection that stores data in the form of a liked-list.
Example:
List(12, 54, 12 , 87)
Option in Scala is a container that contains one single value which can be one of the two distinct values.
Convert List to Option
For this conversion, we need to check if the list is empty or not.
If the list is empty, we will convert in the option value otherwise, leave it the same. This is done using the option.
Scala program to convert list to option
object MyClass {
def listToOption(myList : List[Int] ) : Option[opt] = {
Option(myList).filter(_.nonEmpty).map(opt)
}
case class opt(list : List[Int]) {}
def main(args: Array[String]) {
val List1 = List(21, 43, 54)
val option1 = listToOption(List1)
println(option1)
val List2 = List()
val option2 = listToOption(List2)
println(option2)
}
}
Output
Some(opt(List(21, 43, 54)))
None
Description
In the above code, we have created two lists one empty(List2) and one with integer elements(List1). For converting the list to option, we have created a function named listToOption() which takes in a list and returns an option. Where we have used map and its method to check if the list is empty or not. If it is empty then the option will return None otherwise the list.