Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple scala code: Returning first element from string array

Tags:

scala

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))
like image 781
Miro Avatar asked Feb 25 '13 19:02

Miro


People also ask

How do I access elements in Scala list?

We can use the head() and last() methods of the class List to get the first and last elements respectively.

Which refers to the first element in an array?

first element of an array will be arr[0] which is value of arr[0] and. array means arr and arr names represents base address of the array.

Can you append to an array in Scala?

We can append a Scala array to another using the Concat() method. This takes the arrays as parameters- in order.


2 Answers

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
like image 182
Noah Avatar answered Sep 17 '22 22:09

Noah


The most concise way:

def returnFirstString(a: Array[String]): Option[String]= a.headOption
like image 45
pedrofurla Avatar answered Sep 18 '22 22:09

pedrofurla