Choosing the last element of a list

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)