Stack in Scala Last Updated : 25 Apr, 2019 Comments Improve Suggest changes Like Article Like Report A stack is a data structure that follows the last-in, first-out(LIFO) principle. We can add or remove element only from one end called top. Scala has both mutable and immutable versions of a stack. Syntax : import scala.collection.mutable.Stack var s = Stack[type]() // OR var s = Stack(val1, val2, val3, ...) Operations on Stack Once stack has been created we can either push elements to the stack or pop them out of the stack. Push: We can push element of any type to the stack using push() function. All elements must have same data type. Example : scala // Scala program to // push element // to the stack import scala.collection.mutable.Stack // Creating object object GfG { // Main method def main(args:Array[String]) { var s = Stack[Int]() // pushing values // one at a time s.push(5) s.push(1) s.push(2) println("s:" + s) var s2 = Stack[Int]() // pushing multiple values s2.push(5,1,2) println("s2:" + s2) } } Output:s:Stack(2, 1, 5) s2:Stack(2, 1, 5) Pop: We can pop element from top of the stack using pop function. The function returns the same type as that of elements of the stack. Example : scala // Scala program to // pop element from // top of the stack import scala.collection.mutable.Stack // Creating object object GfG { // Main method def main(args:Array[String]) { var s = Stack[Int]() s.push(5) s.push(1) s.push(2) println(s) // pop element from // top of the stack println("Popped:" + s.pop) println("Popped:" + s.pop) println("Popped:" + s.pop) } } Output:Stack(2, 1, 5) Popped:2 Popped:1 Popped:5 Other Functions Other Functions : Let's discuss some more functions with examples. isEmpty: To check whether the stack is empty. Returns true if it is empty. Example : scala // Scala program to // check if the stack // is empty import scala.collection.mutable.Stack // Creating object object GfG { // Main method def main(args:Array[String]) { var s = Stack[Int]() s.push(5) s.push(1) s.push(2) println(s) // pop element from // top of the stack println("Popped:" + s.pop) println("Popped:" + s.pop) println("Empty:" + s.isEmpty) println("Popped:" + s.pop) // all three elements popped println("Empty:" + s.isEmpty) } } Output:Stack(2, 1, 5) Popped:2 Popped:1 Empty:false Popped:5 Empty:true top: Returns the element that is currently at the top of the stack. Example : scala // Scala program to // print top of stack import scala.collection.mutable.Stack // Creating object object GfG { // Main method def main(args:Array[String]) { var s = Stack[Int]() s.push(5) s.push(1) s.push(2) println(s) println("Top: " + s.top) println("Popped:" + s.pop) println("Top: " + s.top) } } Output:Stack(2, 1, 5) Top: 2 Popped:2 Top: 1 size:Returns the number of elements present in the stack. Example : Scala // Scala program to // print size of the stack import scala.collection.mutable.Stack // Creating object object GfG { // Main method def main(args:Array[String]) { var s = Stack[Int]() s.push(5) s.push(1) s.push(2) println(s) println("Size: " + s.size) println("Popped:" + s.pop) println("Size: " + s.size) } } Output:Stack(2, 1, 5) Size: 3 Popped:2 Size: 2 Comment More infoAdvertise with us Next Article HashMap in Scala M MohammadKhalid Follow Improve Article Tags : Scala Scala scala-collection Similar Reads OverviewScala Programming LanguageScala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language which also provides support to the functional programming approach. Scala programs can convert to bytecodes and can run on the JVM (Java Virtual Machine). Scala stands for S3 min readIntroduction to ScalaScala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language which also provides the support to the functional programming approach. There is no concept of primitive data as everything is an object in Scala. It is designed to express7 min readSetting up the environment in ScalaScala is a very compatible language and thus can very easily be installed into the Windows and the Unix operating systems both very easily. In this tutorial, we learn about how to move on with the installation and the setting up of the environment in Scala. The most basic requirement is that we must3 min readHello World in ScalaThe Hello World! the program is the most basic and first program when you dive into a new programming language. This simply prints the Hello World! on the output screen. In Scala, a basic program consists of the following: object Main Method Statements or Expressions Example: Scala // Scala program2 min readBasicsScala KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. Example: Scala // Scala Program to illustrat2 min readScala IdentifiersIn programming languages, Identifiers are used for identification purpose. In Scala, an identifier can be a class name, method name, variable name or an object name. For example : class GFG{ var a: Int = 20 } object Main { def main(args: Array[String]) { var ob = new GFG(); } } In the above program3 min readData Types in ScalaA data type is a categorization of data which tells the compiler that which type of value a variable has. For example, if a variable has an int data type, then it holds numeric value. In Scala, the data types are similar to Java in terms of length and storage. In Scala, data types are treated same o3 min readVariables in ScalaVariables are simply storage locations. Every variable is known by its name and stores some known and unknown piece of information known as value. So one can define a variable by its data type and name, a data type is responsible for allocating memory for the variable. In Scala there are two types o3 min readControl StatementsScala | Decision Making (if, if-else, Nested if-else, if-else if)Decision making in programming is similar to decision making in real life. In decision making, a piece of code is executed when the given condition is fulfilled. Sometimes these are also termed as the Control flow statements. Scala uses control statements to control the flow of execution of the prog5 min readScala | Loops(while, do..while, for, nested loops)Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Scala provides the different types of loop to handle the condition based situation in the progr5 min readBreak statement in ScalaIn Scala, we use a break statement to break the execution of the loop in the program. Scala programming language does not contain any concept of break statement(in above 2.8 versions), instead of break statement, it provides a break method, which is used to break the execution of a program or a loop3 min readScala | LiteralsAny constant value which can be assigned to the variable is called as literal/constant. The literals are a series of symbols utilized for describing a constant value in the code. There are many types of literals in Scala namely Character literals, String literals, Multi-Line String literals, Boolean4 min readOOP ConceptsClass and Object in ScalaClasses and Objects are basic concepts of Object Oriented Programming which revolve around the real-life entities. Class A class is a user-defined blueprint or prototype from which objects are created. Or in other words, a class combines the fields and methods(member function which defines actions)5 min readInheritance in ScalaInheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in Scala by which one class is allowed to inherit the features(fields and methods) of another class. Important terminology: Super Class: The class whose features are inherited is known as superclass(or a base5 min readOperators in ScalaAn operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Scala as follows: Arithmeti11 min readScala Singleton and Companion ObjectsSingleton Object Scala is more object oriented language than Java so, Scala does not contain any concept of static keyword. Instead of static keyword Scala has singleton object. A Singleton object is an object which defines a single object of a class. A singleton object provides an entry point to yo3 min readScala ConstructorsConstructors are used to initializing the objectâs state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. Scala supports two types of constructors: Primary Constructor When our Scala program contains only one c4 min readScala | PolymorphismPolymorphism is the ability of any data to be processed in more than one form. The word itself indicates the meaning as poly means many and morphism means types. Scala implements polymorphism through virtual functions, overloaded functions and overloaded operators. Polymorphism is one of the most im5 min readScala | MultithreadingA process in which multiple threads executing simultaneously that is called multithreading. It allows you to perform multiple tasks independently. What are Threads in Scala? Threads are lightweight sub-processes which occupy less memory. A multi-threaded program contains two or more threads that can3 min readScala this keywordKeywords are the words in a language that are used to represent some predefined actions or some internal process. We use the this keyword when we want to introduce the current object for a class. Then using the dot operator (.), we can refer to instance variables, methods and constructors by using t2 min readMethodsScala | Functions - BasicsA function is a collection of statements that perform a certain task. One can divide up the code into separate functions, keeping in mind that each function must perform a specific task. Functions are used to put some common and repeated task into a single function, so instead of writing the same co3 min readAnonymous Functions in ScalaIn Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function. Syntax: (z:Int, y:Int)=> z*yOr2 min readScala | ClosuresScala Closures are functions which uses one or more free variables and the return value of this function is dependent of these variable. The free variables are defined outside of the Closure Function and is not included as a parameter of this function. So the difference between a closure function an3 min readRecursion in ScalaRecursion is a method which breaks the problem into smaller sub problems and calls itself for each of the problems. That is, it simply means function calling itself. We can use recursion instead of loops. Recursion avoids mutable state associated with loops. Recursion is quite common in functional p4 min readMethod Overloading in ScalaMethod Overloading is the common way of implementing polymorphism. It is the ability to redefine a function in more than one form. A user can implement function overloading by defining two or more functions in a class sharing the same name. Scala can distinguish the methods with different method sig5 min readMethod Overriding in ScalaMethod Overriding in Scala is identical to the method overriding in Java but in Scala, the overriding features are further elaborated as here, both methods as well as var or val can be overridden. If a subclass has the method name identical to the method name defined in the parent class then it is k8 min readLambda Expression in ScalaLambda Expression refers to an expression that uses an anonymous function instead of variable or value. Lambda expressions are more convenient when we have a simple function to be used in one place. These expressions are faster and more expressive than defining a whole function. We can make our lamb4 min readScala VarargsMost of the programming languages provide us variable length argument mobility to a function, Scala is not a exception. it allows us to indicate that the last argument of the function is a variable length argument. it may be repeated multiple times. It allows us to indicate that last argument of a f2 min readStringsScala StringA string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. Creating a String in Scala There are two ways to create a string in Scala: Here, when the compiler meet to a string literal and creates a string object str. Synt4 min readScala | String InterpolationString Interpolation refers to substitution of defined variables or expressions in a given String with respected values. String Interpolation provides an easy way to process String literals. To apply this feature of Scala, we must follow few rules: String must be defined with starting character as s3 min readScala | StringContextStringContext is a class that is utilized in string interpolation, which permits the end users to insert the variables references without any intermediary in the processed String literals. This class supplies raw, s, and f methods by default as interpolators. The Linear Supertypes here are Serializa2 min readRegular Expressions in ScalaRegular Expressions explain a common pattern utilized to match a series of input data so, it is helpful in Pattern Matching in numerous programming languages. In Scala Regular Expressions are generally termed as Scala Regex. Regex is a class which is imported from the package scala.util.matching.Reg5 min readStringBuilder in ScalaA String object is immutable, i.e. a String cannot be changed once created. In situations where you need to perform repeated modifications to a string, we need StringBuilder class. StringBuilder is utilized to append input data to the internal buffer. We can perform numerous operations with the supp4 min readScala PackagesPackages In ScalaPackage in Scala is a mechanism to encapsulate a group of classes, sub packages, traits and package objects. It basically provides namespace to put our code in a different files and directories. Packages is a easy way to maintain our code which prevents naming conflicts of members of different packa4 min readScala | Package ObjectsMain objective of a package is to keep files modularized and easy to be maintained. So we keep project files in several different folder or directories according to the namespace created, but sometimes we want to some variable, definitions, classes or objects to be accessible to entire package. But3 min readChained Package Clauses in ScalaChained packages are way resolving the visibility of members of a package members. This was introduced in Scala 2.8 as described by Martin Odersky Suppose we have a code like below. Let's break the code and understand what happens here. package x.z object a { b //object b } object b{ a //object a }3 min readFile Handling in ScalaFile Handling is a way to store the fetched information in a file. Scala provides packages from which we can create, open, read and write the files. For writing to a file in scala we borrow java.io._ from Java because we donât have a class to write into a file, in the Scala standard library. We coul3 min readScala TraitScala | TraitsIntroduction to Traits in Scala:In Scala, Traits are a fundamental concept of object-oriented programming that provides a mechanism to reuse code. Traits are similar to interfaces in Java, but with the added advantage of providing concrete implementations of methods as well as the ability to include7 min readScala | Sealed TraitSealed provides exhaustive checking for our application. Exhaustive checking allows to check that all members of a sealed trait must be declared in the same file as of the source file. That means that all the possible known members of a trait that must be included are known by the compiler in advanc4 min readScala | Trait MixinsWe can extend several number of scala traits with a class or an abstract class that is known to be trait Mixins. It is worth knowing that only traits or blend of traits and class or blend of traits and abstract class can be extended by us. It is even compulsory here to maintain the sequence of trait3 min readTrait Linearization in ScalaScala Linearization is a deterministic process which comes into play when an object of a class is created which is defined using inheritance of different traits and classes. linearization helps to resolve the diamond problem which occurs when a class or trait inherits a same property from 2 differen5 min readCollectionsScala ListsA list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala. Lists represents5 min readScala ListBufferA list is a collection which contains immutable data. List represents linked list in Scala. A List is immutable, if we need to create a list that is constantly changing, the preferred approach is to use a ListBuffer. The Scala List class holds a sequenced, linear list of items. A List can be built u6 min readListSet in ScalaA set is a collection which only contains unique items which are not repeatable and a list is a collection which contains immutable data. In scala, ListSet class implements immutable sets using a list-based data structure. Elements are stored in reversed insertion order, That means the newest elemen6 min readScala MapMap is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. Key-value pairs can have any data type. However, data type once used for any key and value must be consistent throughout. Maps are classified into two types: m5 min readScala | ArraysArray is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values. It corresponds to arr6 min readScala | ArrayBufferArray in scala is homogeneous and mutable, i.e it contains elements of the same data type and its elements can change but the size of array size canât change. To create a mutable, indexed sequence whose size can change ArrayBuffer class is used. To use, ArrayBuffer, scala.collection.mutable.ArrayBuf4 min readScala | TupleTuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable. An example of a tuple storing an integer, a string, and boolean value. val name = (15, "Chandan", tr5 min readSet in Scala | Set-1A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request. Syntax: // Immutable set val variable_name: Set[type] = Set(item1, item2, ite3 min readSet in Scala | Set-2Prerequisite: Set in Scala | Set-1Adding items in Mutable SetIn Set, We can only add new elements in mutable set. +=, ++== and add() method is used to add new elements when we are working with mutable set in mutable collection and += is used to add new elements when we are working with mutable set i7 min readBitSet in ScalaA set is a collection which only contains unique items which are not repeatable. A BitSet is a collection of small integers as the bits of a larger integer. Non negative integers sets which represented as array of variable-size of bits packed into 64-bit words is called BitSets. The largest number s5 min readHashSet In ScalaHashSet is sealed class. It extends immutable Set and AbstractSet trait. Hash code is used to store elements. It neither sorts the elements nor maintains insertion order . The Set interface implemented by the HashSet class, backed by a hash table . In Scala, A concrete implementation of Set semantic4 min readStack in ScalaA stack is a data structure that follows the last-in, first-out(LIFO) principle. We can add or remove element only from one end called top. Scala has both mutable and immutable versions of a stack. Syntax : import scala.collection.mutable.Stack var s = Stack[type]() // OR var s = Stack(val1, val2, v3 min readHashMap in ScalaHashMap is a part of Scala Collection's. It is used to store element and return a map. A HashMap is a combination of key and value pairs which are stored using a Hash Table data structure. It provides the basic implementation of Map. Syntax: var hashMapName = HashMap("key1"->"value1", "key2"->"value3 min readTreeSet in ScalaSet is a data structure which allows us to store elements which are unique. The ordering of elements does not guarantee by the Set, than a TreeSet will make elements in a given order. In Scala, TreeSet have two versions: scala.collection.immutable.TreeSet and scala.collection.mutable.TreeSet. Syntax4 min readIterators in ScalaAn iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. An iterator defined for any collection does not load the entire collection into the memory but loads elements one after the other. Ther5 min readScala | OptionThe Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null. Important points : The insta3 min read Like