scala> last(List(1, 1, 2, 3, 5, 8)) res0: Int = 8
for having a result above, I wrote this code:
val yum = args(0).toInt val thrill: def last(a: List[Int]): List[Int] = { println(last(List(args(0).toInt).last) }
What is the problem with this code?
Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want last element in list, use -1 as index.
Method #2 : Using islice() + reversed() The inbuilt functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end.
You can use last
, which returns the last element or throws a NoSuchElementException
, if the list is empty.
scala> List(1, 2, 3).last res0: Int = 3
If you do not know if the list is empty or not, you may consider using lastOption
, which returns an Option
.
scala> List().lastOption res1: Option[Nothing] = None scala> List(1, 2, 3).lastOption res2: Option[Int] = Some(3)
Your question is about List
, but using last
on a infinite collection (e.g. Stream.from(0)
) can be dangerous and may result in an infinite loop.
Another version without using last
(for whatever reason you might need it).
def last(L:List[Int]) = L(L.size-1)
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