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:
need an explanation for this answer? contact us directly to get an explanation for this answer