w3resource

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

Scala Programming List Exercise-15 with Solution

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

Scala Code Editor :

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

Previous: Write a Scala program to find the nth element of a given list.
Next: Write a Scala program to reverse a given list.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.