Scala Stack apply() method with example
Last Updated :
03 Nov, 2019
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:
import scala.collection.mutable.Stack
object GfG
{
def main(args : Array[String])
{
val s 1 = Stack( 1 , 2 , 3 , 4 , 5 )
println(s 1 )
val result = s 1 .apply( 0 )
println( "Element at 0th position: " + result)
}
}
|
Output:
Stack(1, 2, 3, 4, 5)
Element at 0th position: 1
Example #2:
import scala.collection.mutable.Stack
object GfG
{
def main(args : Array[String])
{
val s 1 = Stack( "C++" , "Java" , "Python" , "Scala" )
println(s 1 )
val result = s 1 .apply( 2 )
println( "Element at 2nd position: " + result)
}
}
|
Output:
Stack(C++, Java, Python, Scala)
Element at 2nd position: Python
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...