Reputation: 1806
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
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
Reputation: 12783
The most concise way:
def returnFirstString(a: Array[String]): Option[String]= a.headOption
Upvotes: 5