w3resource

Scala Programming: Calculate the length of a given list

Scala Programming List Exercise-24 with Solution

Write a Scala program to calculate the length of a given list.

Sample Solution:

Scala Code:

object Scala_List {     
  def length[A](nums:List[A]):Int = {
    nums.length
   }  
  def main(args: Array[String]): Unit = {
     val nums1 = List(1,2,3,4)
     println("Original List:")
     println(nums1)
     println("Length of the said list:")   
     println(length(nums1))
     val nums2 = List(1, List(2, 3, 4), List(List(List(5, 6, 7))), List(8, 9), List(10), 11)
     println("Original List:")
     println(nums2)
     println("Length of the said list:")   
     println(length(nums2))    
     val colors = List("Red", "Green", "Black", "Pink", "Orange", "White","Yellow")
     println("Original List:")
     println(colors)
     println("Length of the said list:")
     println(length(colors))
    }
} 

Sample Output:

Original List:
List(1, 2, 3, 4)
Length of the said list:
4
Original List:
List(1, List(2, 3, 4), List(List(List(5, 6, 7))), List(8, 9), List(10), 11)
Length of the said list:
6
Original List:
List(Red, Green, Black, Pink, Orange, White, Yellow)
Length of the said list:
7

Scala Code Editor :

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

Previous: Write a Scala program to split a given list into two lists.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/list/scala-list-exercise-24.php