Scala: Data Types Cheat Sheet

The data types that are available in Scala as shown in the below table:

DatatypeDefault valueDescription
BooleanFalseTrue or False
Byte08 bit signed value. Range:-128 to 127
Short016 bit signed value. Range:-215 to 215-1
Char‘\u000’16 bit unsigned unicode character. Range:0 to 216-1
Int032 bit signed value. Range:-231 to 231-1
Long0L64 bit signed value. Range:-263 to 263-1
Float0.0F32 bit IEEE 754 single-Precision float
Double0.0D64 bit IEEE 754 double-Precision float
StringnullA sequence of character
UnitCoinsides to no value.
NothingIt is a subtype of every other type and it contains no value.
AnyIt is a supertype of all other types
AnyValIt serve as value types.
AnyRefIt serves as reference types.

Scala: Variables Cheat Sheet

Variable Data Types

val or val VariableName : DataType = [Initial Value]

If you do not assign any initial value to a variable, then it is valid as follows

var myVar :Int; 
val myVal :String;

Multiple assignments

val (myVar1: Int, myVar2: String) = Pair(80, "Ahi")

Another way of defining variable:

val (myVar1, myVar2) = Pair(80, "Ahi")

Scala: Packages Cheat Sheet

Declaration of Package

package package_name
// Scala classes
// traits
// objects..

Chained methods

package x.y.z
// members of z

Or

package x
package y
package z
// member of z

Nesting packages

package x{
   // members of x {as required}
   package y{
      // members of y{as required}
      package z{
         // members of z{as required}
      }
   }
}

Adding Members to Packages

// file named as faculty.scala
package college
class faculty{
   def faculymethod(){}
}

Wildcard import

import scala.collection._

Selective import

import scala.collection.Vector

Or

import scala.collection.{Vector, Sequence}

Renaming import

import scala.collection.{Vector => Vec14}

Import all from java.util except Date

import java.util.{Date => _, _}

Scala: Options Cheat Sheet

OptionDescription
Some(42)Construct a non empty optional value.
NoneThe singleton empty optional value.
Option(null) == None Option(obj.unsafeMethod)
but
Some(null) != None
Null-safe optional value factory.
val optStr: Option[String] = None
same as
val optStr = Option.empty[String]
Explicit type for empty optional value.
Factory for empty optional value.
val name: Option[String] =
request.getParameter("name")
val upper = name.map {
_.trim
} filter {
_.length != 0
} map {
_.toUpperCase } println(upper.getOrElse(""))
Pipeline style.
val upper = for {
name <- request.getParameter("name")
trimmed <- Some(name.trim)
if trimmed.length != 0
upper <- Some(trimmed.toUpperCase)
} yield upper println(upper.getOrElse(""))
For-comprehension syntax.
option.map(f(_))
same as
option match {
case Some(x) => Some(f(x))
case None => None
}
Apply a function on the optional value.
option.flatMap(f(_))
same as
option match {
case Some(x) => f(x)
case None => None
}
Same as map but function must return an optional value.
optionOfOption.flatten
same as
optionOfOption match {
case Some(Some(x)) => Some(x)
case _ => None
}
Extract nested option.
option.foreach(f(_))
same as
option match {
case Some(x) => f(x)
case None => ()
}
Apply a procedure on optional value.
option.fold(y)(f(_))
same asoption match {
case Some(x) => f(x)
case None => y
}
Apply function on optional value, return default if empty.
option.collect {
case x => ...
}
same as
option match {
case Some(x) if f.isDefinedAt(x) => ...
case Some(_) => None case None => None
}
Apply partial pattern match on optional value.
option.isDefined
same asoption match {
case Some(_) => true
case None => false
}
true if not empty.
option.isEmpty
same as
option match {
case Some(_) => false
case None => true
}
true if empty.
option.nonEmpty
same asoption match {
case Some(_) => true
case None => false
}
true if not empty.
option.size
same as
option match {
case Some(_) => 1
case None => 0
}
0 if empty, otherwise 1.
option.orElse(Some(y))
same as
option match {
case Some(x) => Some(x)
case None => Some(y)
}
Evaluate and return alternate optional value if empty.
option.getOrElse(y)
same as
option match {
case Some(x) => x
case None => y
}
Evaluate and return default value if empty.
option.get
same as
option match {
case Some(x) => x
case None => throw new Exception
}
Return value, throw exception if empty.
option.orNull
same as
option match {
case Some(x) => x
case None => null
}
Return value, null if empty.
option.filter(f)
same as
option match {
case Some(x) if f(x) => Some(x)
case _ => None
}
Optional value satisfies predicate.
option.filterNot(f(_))
same as
option match {
case Some(x) if !f(x) => Some(x)
case _ => None
}
Optional value doesn’t satisfy predicate.
option.exists(f(_))
same as
option match {
case Some(x) if f(x) => true
case Some(_) => false
case None => false
}
Apply predicate on optional value or false if empty.
option.forall(f(_))
same as
option match {
case Some(x) if f(x) => true
case Some(_) => false
case None => true
}
Apply predicate on optional value or true if empty.
option.contains(y)
same as
option match {
case Some(x) => x == y
case None => false
}
Checks if value equals optional value or false if empty.

Scala: Pattern matching Cheat Sheet

Use case in function args for pattern matching:

(xs zip ys) map { 
   case (x, y) => x * y 
}

`v42` with backticks is interpreted as the existing val v42, and “Not 42” is printed:

val v42 = 42 
3 match { 
   case `v42` => println("42") 
   case _ => println("Not 42") 
}

UppercaseVal is treated as an existing val, rather than a new pattern variable, because it starts with an uppercase letter. Thus, the value contained within UppercaseVal is checked against 3, and “Not 42” is printed:

val UppercaseVal = 42 
3 match { 
   case UppercaseVal => println("42") 
   case _ => println("Not 42") 
}

Scala: Class and Object Cheat Sheet

Classes

Basic Syntax:

class Class_name{
// methods and feilds
}

Some optional attributes:

  • Keyword class: A class keyword is used to declare the type of class.
  • Class name: The name should begin with an initial letter (capitalized by convention).
  • Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  • Traits(if any): A comma-separated list of traits implemented by the class, if any, preceded by the keyword extends. A class can implement more than one trait.
  • Body: The class body is surrounded by { } (curly braces).

Object

An object consists of :

  • State: It is represented by attributes of an object. It also reflects the properties of an object.
  • Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects.
  • Identity: It gives a unique name to an object and enables one object to interact with other objects.

In Scala, an object of a class is created using the new keyword. The syntax of creating an object in Scala is:

var obj = new Objectname();

Object orientation

class C(x: R)Constructor params – x is only available in class body.
class C(val x: R)
var c = new C(4)
c.x
Constructor params – automatic public member defined.
class C(var x: R) {
assert(x > 0, "positive please")
var y = x
val readonly = 5
private var secret = 1
def this = this(42)
}
Constructor is class body.
Declare a public member.
Declare a gettable but not settable member.
Declare a private member.
Alternative constructor.
new {
...
}
Anonymous class.
abstract class D { ... }Define an abstract class (non-createable).
class C extends D { ... }Define an inherited class.
class D(var x: R)
class C(x: R) extends D(x)
Inheritance and constructor params (wishlist: automatically pass-up params by default).
object O extends D { ... }Define a singleton (module-like).
trait T { ... }
class C extends T { ... }
class C extends D with T { ... }
Traits.
Interfaces-with-implementation. No constructor params.
trait T1; trait T2
class C extends T1 with T2
class C extends D with T1 with T2
Multiple traits.
class C extends D { override def f = ...}Must declare method overrides.
new java.io.File("f")Create object.

Scala: Access Modifiers Cheat Sheet

Three types of access modifiers available in Scala:

MODIFIERCLASSCOMPANIONSUBCLASSPACKAGEWORLD
No Modifier/PublicYesYesYesYesYes
ProtectedYesYesYesNo *No
PrivateYesYesNoNo *No

Scala: Operators Cheat Sheet

Arithmetic Operators

OperatorDescriptionExample
+Adds two operandsx+y
Subtracts second operand from the firstx-y
*Multiplies both operandsx*y
/Divides numerator by de-numeratorx/y
%Modulus operator returns the remainder when the first operand is divided by the second.x%y will give 0
**Returns exponential(power) of the operandsc**y

Relational Operators

OperatorDescriptionExample
==Checks if the values of two operands are equal or not, if yes then condition becomes true.(3==3) return true
!=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(3!=3) return false
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(7>3) return true
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(7<3) return false
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(3>=3) return true
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(3<=3) return true

Logical Operators

OperatorDescriptionExample
&&It is called Logical AND operator. If both the operands are non zero then condition becomes true.(a&&b) is false.
||It is called Logical OR Operator. If any of the two operands is non zero then condition becomes true.(a||b) is true.
!It is called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(a&&b) is true.

Assignment Operators

OperatorDescriptionExample
=Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C – A
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A
<<=Left shift AND assignment operatorC <<= 2 is same as C = C << 2
>>=Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
&=Bitwise AND assignment operatorC &= 2 is same as C = C & 2
^=bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2
|=bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2

Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Below is the truth tables for &, |, and ^

pqp & qp | qp ^ q
00000
01011
11110
10011

The Bitwise operators supported by Scala language is listed in the following table. Assume variable A holds 60 and variable B holds 13

OperatorDescriptionExample
&Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12, which is 0000 1100
|Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61, which is 0011 1101
^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49, which is 0011 0001
~Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits.(~A ) will give -61, which is 1100 0011 in 2’s complement form due to a signed binary number.
<<Binary Left Shift Operator. The bit positions of the left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240, which is 1111 0000
>>Binary Right Shift Operator. The Bit positions of the left operand value is moved right by the number of bits specified by the right operand.A >> 2 will give 15, which is 1111
>>>Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.A >>>2 will give 15 which is 0000 1111

Operators Precedence

CategoryOperatorAssociativity
Postfix() []Left to right
Unary! ~Right to left
Multiplicative* / %Left to right
Additive+ –Left to right
Shift>> >>> <<Left to right
Relational> >= < <=Left to right
Equality== !=Left to right
Bitwise AND&Left to right
Bitwise XOR^Left to right
Bitwise OR|Left to right
Logical AND&&Left to right
Logical OR||Left to right
Assignment= += -= *= /= %= >>= <<= &= ^= |=Right to left
Comma,Left to right

Scala: If-Else Statements Cheat Sheet

if Statement

if(Boolean_expression) {
   // Statements will execute if the Boolean expression is true
}

if-else Statement

if(Boolean_expression){
   //Executes when the Boolean expression is true
} else{
   //Executes when the Boolean expression is false
}

if-else-if-else Statement

if(Boolean_expression 1){
   //Executes when the Boolean expression 1 is true
} else if(Boolean_expression 2){
   //Executes when the Boolean expression 2 is true
} else if(Boolean_expression 3){
   //Executes when the Boolean expression 3 is true
} else {
   //Executes when the none of the above condition is true.
}

Nested if-else Statement

if(Boolean_expression 1){
   //Executes when the Boolean expression 1 is true
   
   if(Boolean_expression 2){
      //Executes when the Boolean expression 2 is true
   }
}

Scala: Loop Statements Cheat Sheet

while Loop

while (condition)
{
    // Code to be executed
}

do..while Loop

do {

// statements to be Executed

} while(condition);

for Loop

for( var x <- Range ){
   statement(s);
}

break Statement

// import following package
import scala.util.control._

// create a Breaks object as follows
val loop = new Breaks;

// Keep the loop inside breakable as follows
loop.breakable {
   // Loop will go here
   for(...){
      ....
      
      // Break will go here
      loop.break;
   }
}

Or

import scala.util.control.Breaks._
breakable 
{
 for(..)
{
 code..
 break
}
}

Scala: Functions Cheat Sheet

Function Declarations

def functionName ([list of parameters]) : [return type]

Function Definitions

def functionName ([list of parameters]) : [return type] = {
   function body
   return [expr]
}

Calling Functions

functionName( list of parameters )

In the Second way, a user can also call the function with the help of the instance and dot notation as follows:

[instance].function_name(paramter_list)

Functions Call-by-Name

def callByValue(x: Int)

Nested Functions

def FunctionName1( perameter1, peramete2, ..) = {
def FunctionName2() = {
// code
}
}

Partially Applied Functions

val multiply = (a: Int, b: Int, c: Int) => a * b * c

// less arguments passed
val f = multiply(1, 2, _: Int)

Named Arguments

Function Definition : def createArray(length:int, capacity:int);
Function calling : createArray(capacity=20, length:10);

Recursion Functions

Example:

// Scala program of factorial using recursion
 
// Creating object
object sample
{
   // Function define
   def fact(n:Int): Int=
   {
      if(n == 1) 1
      else n * fact(n - 1)
   }
 
   // Main method
   def main(args:Array[String])
   {
      println(fact(3))
   }
}

=> Output

6

Higher-Order Functions

Example:

object Demo {
   def main(args: Array[String]) {
      println( apply( layout, 10) )
   }

   def apply(f: Int => String, v: Int) = f(v)

   def layout[A](x: A) = x.toString()
}

=> Output

10

Anonymous Functions 

(z:Int, y:Int)=> z*y
Or
(_:Int)*(_Int)

Currying Functions

def function name(argument1, argument2) = operation

Scala: Strings Cheat Sheet

Creating a String

var str = "Hello world!";

or

var str:String = "Hello world!";

Note: If you need to append to the original string, then use StringBuilder class.

Get length of the string

var len = str.length();

Concatenating strings in Scala

The String class includes a method for concatenating two strings −

str1.concat(string2);

Or

Strings are more commonly concatenated with the + operator:

"My name is:" + " John" + "!"

Creating format string

Example:

// Scala program to illustrate how to
// Creating format string
object Main
{

   // two strings 
   var stringVar = "Hello world!"
   var intVar = 14
   var floatVar = 14.07

   // Main function 
   def main(args: Array[String]) 
   { 

       // using format() function 
       println("%s, %d, %f".format(stringVar, intVar, floatVar)); 
   } 
}

=> Output

Hello world!, 14, 14.07

Important string functions

FunctionDescription
char charAt(int index)This function returns the character at the given index.
String replace(char ch1, char ch2)This function returns a new string in which the element of ch1 is replaced by the ch2.
String[] split(String reg)This function splits the string around matches of the given regular expression.
String substring(int i)This function returns a new string that is a substring of the given string.
String trim()This function returns a copy of the string, with starting and ending whitespace removed.
boolean startsWith(String prefix)This function is used to check if the given string starts with the specified prefix or not.

Scala: Arrays Cheat Sheet

One Dimensional Array

This array contains only one row for storing the values. All values of this array are stored contiguously starting from 0 to the array size.

Syntax:

var arrayname = new Array[datatype](size)

Multidimensional Arrays

Multidimensional arrays contain more than one row to store the values. Scala has a method Array.ofDim to create Multidimensional arrays in Scala.

Syntax:

var array_name = Array.ofDim[ArrayType](N, M)
 or  
var array_name = Array(Array(elements), Array(elements)

Here N is number of rows and M is number of Columns. 

Scala Array Methods

MethodsDescription
def apply( x: T, xs: T* ): Array[T]Creates an array of T objects, where T can be Unit, Double, Float, Long, Int, Char, Short, Byte, Boolean.
def concat[T]( xss: Array[T]* ): Array[T]Concatenates all arrays into a single array.
def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): UnitCopy one array to another. Equivalent to Java’s System.arraycopy(src, srcPos, dest, destPos, length).
def empty[T]: Array[T]Returns an array of length 0
def iterate[T]( start: T, len: Int )( f: (T) => T ): Array[T]Returns an array containing repeated applications of a function to start value.
def fill[T]( n: Int )(elem: => T): Array[T]Returns an array that contains the results of some element computation a number of times.
def fill[T]( n1: Int, n2: Int )( elem: => T ): Array[Array[T]]Returns a two-dimensional array that contains the results of some element computation a number of times.
def iterate[T]( start: T, len: Int)( f: (T) => T ): Array[T]Returns an array containing repeated applications of a function to start value.
def ofDim[T]( n1: Int ): Array[T]Creates an array with given dimensions.
def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]]Creates a 2-dimensional array
def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]]Creates a 3-dimensional array
def range( start: Int, end: Int, step: Int ): Array[Int]Returns an array containing equally spaced values in some integer interval.
def range( start: Int, end: Int ): Array[Int]Returns an array containing a sequence of increasing integers in a range.
def tabulate[T]( n: Int )(f: (Int)=> T): Array[T]Returns an array containing values of a given function over a range of integer values starting from 0.
def tabulate[T]( n1: Int, n2: Int )( f: (Int, Int ) => T): Array[Array[T]]Returns a two-dimensional array containing values of a given function over ranges of integer values starting from 0.

Scala: Collections Cheat Sheet

Lists

Scala’s List[T] is a linked list of type T.

Below is an example of lists defined for various data types:

// List of Strings
val fruit: List[String] = List("bananas", "watermelons", "apples")

// List of Integers
val nums: List[Int] = List(1, 2, 3, 4)

// Empty List.
val empty: List[Nothing] = List()

// Two dimensional list
val dim: List[List[Int]] =
   List(
      List(1, 0, 0),
      List(0, 1, 0),
      List(0, 0, 1)
   )

Sets

A set is a collection of pairwise different elements of the same type.

Syntax:

// Empty set of integer type
var s : Set[Int] = Set()

// Set of integer type
var s : Set[Int] = Set(2,4,6,8)

or 

var s = Set(2,4,6,8)

Maps

A Map is a collection of key/value pairs. Any value can be retrieved based on its key.

Example

// Empty hash table whose keys are strings and values are integers:
var A:Map[Char,Int] = Map()

// A map with keys and values.
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")

Tuples

Unlike an array or list, a tuple can hold objects with different types.

Example:

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 )
   }
}

Iterators

An iterator is not a collection, but rather a way to access the elements of a collection one by one.

Example:

object Demo {
   def main(args: Array[String]) {
      val it = Iterator("a", "number", "of", "words")
      
      while (it.hasNext){
         println(it.next())
      }
   }
}