Open In App

Scala List apply() method with example

Last Updated : 26 Jul, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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 m1 = List(1, 3, 5, 2)
          
        // Applying apply method
        val res = m1.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 m1 = List(1, 3, 5, 2)
          
        // Applying apply method
        val res = m1.apply(0)
          
        // Displays output
        println(res)
      
    }
}


Output:

1


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads