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))
We can use the head() and last() methods of the class List to get the first and last elements respectively.
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.
We can append a Scala array to another using the Concat() method. This takes the arrays as parameters- in order.
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
The most concise way:
def returnFirstString(a: Array[String]): Option[String]= a.headOption
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With