Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala
list
communitycreator

What is the List.length method in Scala?

Harris Amjad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

The List.length function in Scala returns the number of elements in a list. In short, this function is used to get the current size of a list.

Figure 1 shows a visual representation of the List.length function:

Figure 1: Visual representation of the list.length function

Syntax

list_name.length
// where the list_name is the name of the list object

Parameters

This function does not require a parameter.

Return value

This function returns the number of elements in the List object and is used to get the current size of the list.

Code

The following code shows how to use the List.length function in Scala:

import scala.collection.mutable.Map
object Main extends App {
//filled list
var list_1 = List(1,3,4,2,0)
//list_1 elements and length
println("The list_1 elements: " + list_1);
println("The list_1 is empty: " + list_1.length);
//empty list
var list_2 = List()
//list_2 elements and length
println("The list_2 elements: " + list_2);
println("The list_2 is empty: " + list_2.length);
}

Explanation

The code above initializes two List objects: list_1 and list_2. The length function returns the size of both List objects, i.e., 5 and 0, respectively.

RELATED TAGS

scala
list
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring