Miro
Miro

Reputation: 1806

Simple scala code: Returning first element from string array

I don't know how to fix this code. It "explodes" somewhere in returnFirstString but I don't know why. Also, I don't know how to properly display result using println. Is this approach ok.

So here's the code:

def returnFirstString(a: Array[String]): Option[String]=
{
    if(a.isEmpty) { None }
    Some(a(0))
}
val emptyArrayOfStrings = Array.empty[String]
println(returnFirstString(emptyArrayOfStrings))

Upvotes: 10

Views: 31343

Answers (2)

Noah
Noah

Reputation: 13959

You're not properly returning the None:

  def returnFirstString(a: Array[String]): Option[String] = {
    if (a.isEmpty) {
      None
    }
    else {
      Some(a(0))
    }
  }

Also, there's already a method for this on most scala collections:

emptyArrayOfStrings.headOption

Upvotes: 16

pedrofurla
pedrofurla

Reputation: 12783

The most concise way:

def returnFirstString(a: Array[String]): Option[String]= a.headOption

Upvotes: 5

Related Questions