Scala List Examples

My notes on scala.lists :

– scala.list is different from java.util.List

– scala.list isĀ  ‘immutable sequence of objects’

– scala list doesn’t support append operation

Some Scala list operators and methods:

  • ::: – for list concatenation
    scala > val oneTwo = List(1, 2)
    scala > val threeFour = List(3, 4)
    scala > val oneTwoThreeFour = oneTwo ::: threeFour
  • :: – cons operator – prepends a new element to the begging of an existing list
    scala > val twoThree = List(2,3)
    scala > valOneTwoThree = 1 :: twoThree
  • cons operator is method of right hand operand
    scala > val oneTwoThree = 1 :: 2 :: 3 :: Nil
  • index operation : thrill(2)
    scala > val thrill = “Will” :: “fill” :: “until” :: Nil
    scala > thrill(2)
  • create empty Scala’s list :
    scala > List()
    scala > Nil
  • create a new List[String]
    scala > List(“Cool”, “tools”, “rule”)
  • counts the number of list elements
    scala > val thrill = “Will” :: “fill” :: “until” :: Nil
    scala > thrill.count(s=>s.length == 4)

Reference :

1. Programming in Scala: A Comprehensive Step-by-step Guide

Leave a Reply

Your email address will not be published. Required fields are marked *