Scala Stack apply() method with example

In Scala Stack class, the apply() method is utilized to return an element at a given position in the stack. The top of the stack corresponds to the element at 0th position and so on.

Method Definition: def apply(idx: Int): A

Return Type: It returns an element at a given position in the stack.

Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of apply() 
// method 
   
import scala.collection.mutable.Stack 
   
// Creating object 
object GfG 
       
    // Main method 
    def main(args:Array[String]) 
    
           
        // Creating a stack
        val s1 = Stack(1, 2, 3, 4, 5
           
        // Print the stack
        println(s1)
       
        // Applying apply method    
        val result = s1.apply(0)
           
        // Display output
        println("Element at 0th position: " + result) 
   
    

chevron_right


Output:

Stack(1, 2, 3, 4, 5)
Element at 0th position: 1

Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of apply() 
// method 
   
import scala.collection.mutable.Stack 
   
// Creating object 
object GfG 
       
    // Main method 
    def main(args:Array[String]) 
    
           
        // Creating a stack
        val s1 = Stack("C++", "Java", "Python", "Scala"
           
        // Print the stack
        println(s1)
       
        // Applying apply method    
        val result = s1.apply(2)
           
        // Display output
        println("Element at 2nd position: " + result) 
   
    

chevron_right


Output:

Stack(C++, Java, Python, Scala)
Element at 2nd position: Python



My Personal Notes arrow_drop_up

Coder Machine Learner Social Activist Vocalist

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.