Friday, 6 May 2016

Scala Useful Code Snippets for Beginners(Part-2): Lists

Introduction

In Scala, most popular and frequently used Collection utility is List. It is an Immutable collection. It accepts null values and duplicate elements.

It is available in scala.collection.immutable package.

Empty List is represented using 'Nil' construct. Just like Strings uses '++'  function ( But Not an operator)  for String concatenation,  List uses 'cons' operator to concatenate lists.

List uses '+' function ( But Not an operator) to add a new element at the end of the existing List. 

Let us explore Scala List with some examples.

Examples:

To create empty list

scala> val emptyList1 = List()

emptyList1: List[Nothing] = List()

To create empty list of 'Nil.type' type

scala> val emptyList2 = Nil
emptyList2: scala.collection.immutable.Nil.type = List()

To create a List with 1 and 2 values using 'cons' operator

scala> val list3 = 1 :: 2 :: Nil
list3: List[Int] = List(1, 2)

To create a List using List companion object

scala> val list3 = List(1,2)
list3: List[Int] = List(1, 2)

To combine/concatenate two Lists of same types:

scala> val subList1 = List(1,2,3)
subList1: List[Int] = List(1, 2, 3)

scala> val subList2 = List(4,5,6)
subList2: List[Int] = List(4, 5, 6)

scala> val fullList = subList1 ++ subList2
fullList: List[Int] = List(1, 2, 3, 4, 5, 6)

To use map function

scala> List(1,2,3,4,5).map(i => i+1)
res0: List[Int] = List(2, 3, 4, 5, 6)

scala> List(1,2,3,4,5).map { i => i+1 }
res1: List[Int] = List(2, 3, 4, 5, 6)

To eliminate boilerplate code in using parameters

scala> List(1,2,3,4,5).map { _ + 1 }
res2: List[Int] = List(2, 3, 4, 5, 6)



Please drop your comments or value suggestions about my posts.

Thank you.