w3resource

Scala Programming: Find an element from the last position of a given list


Write a Scala program to find an element from the last position of a given list.

Sample Solution:

Scala Code:

object Scala_List {
  def last_Nth_num[A](nums: List[A], n: Int ): A = {
    if (n <= 0) throw new IllegalArgumentException("Nth position is less than 1!")
    if (n > nums.length) throw new NoSuchElementException("Nth position greater than list length!")
    nums.takeRight(n).head
   } 
     
   def main(args: Array[String]): Unit = {
         val nums = List(1, 2, 3, 4, 5, 7, 9, 11, 14, 12, 16)
         println("Result: " + last_Nth_num(nums, 3));
         println("Result: " + last_Nth_num(nums, 6));
         println("Result: " + last_Nth_num(nums, 0));
         }
}

Sample Output:

Result: 14
Result: 7

Go to:


PREV : Write a Scala program to find the nth element of a given list.
NEXT : Write a Scala program to reverse a given list.

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.