
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala - Tuples
Scala tuple combines a fixed number of items together so that they can be passed around as a whole. Unlike an array or list, a tuple can hold objects with different types but they are also immutable.
The following is an example of a tuple holding an integer, a string, and the console.
val t = (1, "hello", Console)
Which is syntactic sugar (short cut) for the following −
val t = new Tuple3(1, "hello", Console)
The actual type of a tuple depends upon the number and of elements it contains and the types of those elements. Thus, the type of (99, "Luftballons") is Tuple2[Int, String]. The type of ('u', 'r', "the", 1, 4, "me") is Tuple6[Char, Char, String, Int, Int, String]
Tuples are of type Tuple1, Tuple2, Tuple3 and so on. There currently is an upper limit of 22 in the Scala if you need more, then you can use a collection, not a tuple. For each TupleN type, where 1 <= N <= 22, Scala defines a number of element-access methods. Given the following definition −
val t = (4,3,2,1)
To access elements of a tuple t, you can use method t._1 to access the first element, t._2 to access the second, and so on. For example, the following expression computes the sum of all elements of t.
val sum = t._1 + t._2 + t._3 + t._4
You can use Tuple to write a method that takes a List[Double] and returns the count, the sum, and the sum of squares returned in a three-element Tuple, a Tuple3[Int, Double, Double]. They are also useful to pass a list of data values as messages between actors in concurrent programming.
Example
Try the following example program. It shows how to use a tuple.
object Demo { def main(args: Array[String]) { val t = (4,3,2,1) val sum = t._1 + t._2 + t._3 + t._4 println( "Sum of elements: " + sum ) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Commands
\>scalac Demo.scala \>scala Demo
Output
Sum of elements: 10
Iterate over the Tuple
You can use Tuple.productIterator() method to iterate over all the elements of a Tuple.
Example
Try the following example program to iterate over tuples.
object Demo { def main(args: Array[String]) { val t = (4,3,2,1) t.productIterator.foreach{ i =>println("Value = " + i )} } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Commands
\>scalac Demo.scala \>scala Demo
Output
Value = 4 Value = 3 Value = 2 Value = 1
Converting to String
You can use Tuple.toString() method to concatenate all the elements of the tuple into a string. Try the following example program to convert to String.
Example
object Demo { def main(args: Array[String]) { val t = new Tuple3(1, "hello", Console) println("Concatenated String: " + t.toString() ) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Concatenated String: (1,hello,scala.Console$@281acd47)
Swap the Elements
You can use Tuple.swap method to swap the elements of a Tuple2.
Example
Try the following example program to swap the elements.
object Demo { def main(args: Array[String]) { val t = new Tuple2("Scala", "hello") println("Swapped Tuple: " + t.swap ) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Swapped tuple: (hello,Scala)
Creating Tuples
Tuples can be created with any number of elements, up to a maximum of 22. Each element can be of a different type. Here is how you create a tuple with more elements:
Example
object Demo { def main(args: Array[String]) = { val t = (1, "Scala", 3.14, 'a', true) println("Tuple: " + t) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Tuple: (1,Scala,3.14,a,true)
Tuple as Return Type
Tuples can be used as return types for functions that need to return multiple values. So it is easy to group related data together and return them from a function without creating a new class or structure.
Example
object Demo { def main(args: Array[String]) = { def getPersonInfo() = { ("John", 25, "Software Engineer") } val personInfo = getPersonInfo() println("Name: " + personInfo._1) println("Age: " + personInfo._2) println("Occupation: " + personInfo._3) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Name: John Age: 25 Occupation: Software Engineer
Destructuring Tuples
You can destructure a tuple to extract its elements into individual variables. This is used for easily accessing tuple elements without using the ._n notation.
Example
object Demo { def main(args: Array[String]) = { val personInfo = ("John", 25, "Software Engineer") val (name, age, occupation) = personInfo println("Name: " + name) println("Age: " + age) println("Occupation: " + occupation) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Name: John Age: 25 Occupation: Software Engineer
Zipping Lists into Tuples
You can zip two lists together to create a list of tuples. This is used when you want to pair elements from two lists.
Example
Consider following example for zipping lists into tuples -
object Demo { def main(args: Array[String]) = { val list1 = List(1, 2, 3) val list2 = List("one", "two", "three") val zipped = list1.zip(list2) println("Zipped List: " + zipped) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Zipped List: List((1,one), (2,two), (3,three))
Converting Tuple to Map
You can convert a list of tuples into a map. This is used when you have pairs of related data that you want to use as key-value pairs in a map.
Example
Consider following example for converting tuple to map -
object Demo { def main(args: Array[String]) = { val listOfTuples = List((1, "one"), (2, "two"), (3, "three")) val map = listOfTuples.toMap println("Map: " + map) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Map: Map(1 -> one, 2 -> two, 3 -> three)
Scala Tuple Summary
- Tuples combine a fixed number of items together. So these can be passed around as a whole.
- Tuples can hold objects of different types and are immutable.
- Elements in a tuple can be accessed using the ._n notation.
- Tuples can be nested and can contain up to 22 elements.
- You can use tuples to return multiple values from a method and to pass a list of data values as messages between actors in concurrent programming.
- Various operations can be performed on tuples, like, iterating, converting to strings, swapping elements, destructuring, zipping lists, and converting to maps.