Sonu
Sonu

Reputation: 665

How to get last element of an array in scala

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(" ");
 }

Upvotes: 32

Views: 43787

Answers (2)

Mark Lister
Mark Lister

Reputation: 1143

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)

Upvotes: 17

BeniBela
BeniBela

Reputation: 16907

Just use last:

 var num = line_.split(" ").last;

Upvotes: 58

Related Questions