Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala
apply

What is the apply method for lists in Scala?

Sarvech Qadir

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.

The apply() method enables us to access an element by its particular index position in lists in Scala.

Syntax

def apply(n: Int): A

Use

List.apply(x)
// where x is an integer. 

Calling .apply() on a list returns the value present at the index passed represented by x in the syntax above.

Code

Let’s have a look at a coding example to understand it further:

object Main extends App {
val mylist = List("hello", "hi", "xyz", "hey")
// the apply method
val x = mylist.apply(0)
println("apply at position 0 : " + x)
val y = mylist.apply(2)
println("apply at position 2 : " + y)
}

RELATED TAGS

scala
apply

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved

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.

Keep Exploring