32

How to get the last element from array if present. In below code num contains array of elements

 var line_ = ln.trim 
 if(!line_.isEmpty) {
     var num = line_.split(" ");
 }

2 Answers 2

58

Just use last:

 var num = line_.split(" ").last;
Sign up to request clarification or add additional context in comments.

2 Comments

How about val num = ln.trim.split(" ").last. Do you really like to read few lines instead of one?
@pawel.panasewicz: like Mark said, that will not work if the line is empty. Good thing the isEmpty check was already there...
17

Last will work if the Array is not empty. You might prefer lastOption:

scala> Array.empty[String].lastOption
 res5: Option[String] = None

 scala> "ab".toArray.lastOption
 res6: Option[Char] = Some(b)

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.