Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert/wrap a sequence in scala to an Option[Seq] so that if the list is empty, the Option is None

I could do this with an if an statement, but there is probably a "scala" way to do this.

  def notScalaConv(in: Seq[String]): Option[Seq[String]] = {
    if (in.isEmpty)
      None
    else
      Option(in)
  }
like image 893
marathon Avatar asked Feb 24 '17 18:02

marathon


People also ask

What are option some and none in Scala?

An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.

What is getOrElse in Scala?

As we know getOrElse method is the member function of Option class in scala. This method is used to return an optional value. This option can contain two objects first is Some and another one is None in scala. Some class represent some value and None is represent a not defined value.

What is some function 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.

Is defined Scala?

Noun. Ladder; sequence. (anatomy) Ladder-like structure in the cochlea of a mammal's ear.


1 Answers

You can lift your Seq to an Option, and then filter it. Like this:

 def notScalaConv(in: Seq[String]): Option[Seq[String]] = {
     Option(in).filter(_.nonEmpty)
 }
like image 58
marstran Avatar answered Sep 28 '22 15:09

marstran