Sunday, February 21, 2016

for loop in Scala


In Scala, the for is actually foreach, you write it as follows:

val filesHere = (new java.io.File(".")).listFiles
for (file < - filesHere)
println(file)

for (i < - 1 to 4) //gives 1,2,3,4
for (i < - 1 until 4) //gives 1,2,3

We can not only iterate over a sequence but also filter it as follows:

for (
file < - fileshere
if file.isFile;
if file.getName.endsWith(".scala")
) println(file)

Nested loop:

for (
file < - fileshere
if file.getName.endsWith(".scala");
line < - fileLines(file)
if line.trim.matches(pattern)
) println(file +": "+ line.trim)

Creating new collection:

def scalaFiles =
for {
file < - fileshere>
if file.getName.endsWith(".scala")
} yield file

Immutable objects



Positives:
  1. State does not change overtime
  2. Can pass them around freely
  3. Threads don't share an object 
  4. Can identify an object by its hash
Negatives:
  1. Large objects result in performance hit when they are duplicated