10

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))

2 Answers 2

16

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
Sign up to request clarification or add additional context in comments.

Comments

5

The most concise way:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.