Scala List apply() method with example
The apply() method is utilized to select an element in the list by its index.
Method Definition: def apply(n: Int): A
Return Type: It returns an element from the given list by its index which is present in the apply method as argument.
Example #1:
// Scala program of apply() // method // Creating object object GfG { // Main method def main(args : Array[String]) { // Creating a list val m 1 = List( 1 , 3 , 5 , 2 ) // Applying apply method val res = m 1 .apply( 3 ) // Displays output println(res) } } |
Output:
2
Example #2:
// Scala program of apply() // method // Creating object object GfG { // Main method def main(args : Array[String]) { // Creating a list val m 1 = List( 1 , 3 , 5 , 2 ) // Applying apply method val res = m 1 .apply( 0 ) // Displays output println(res) } } |
Output:
1