Scala Basic Data Type

The more you learn, the more you might be lost. So going back to original basic part is a good choice to find way back. So here I list basic data type and how to use it in Scala. Very simple, but very useful.

1. Array

val greetStrings = new Array[String](3)

for (i <- 0 to 2)
  print(greetStrings(i))

greetStrings(0) = "hello"

greetStrings.update(0, "hello")

val numNames= Array("zero", "one", "two")
val numNames1 = Array.apply("zero", "one", "two")

2. Lists

val one = List(1,2,3)
val two = List(4,5)
val three = one ::: two // List(1,2,3,4,5)
val three1 = 1 :: two // List(1,1,2,3)
val three2 = 1 :: 2 :: 3 :: Nil // List(1,2,3)

3. Tuples

val pair = (1, "2")
println(pair._1)

4. Sets and Maps

var jetSet = Set("boeing", "airbus")
jetSet += "Lear"
println(jetSet.contains("abc"))
import scala.collection.immutable.HashSet
val hashSet = HashSet("a", "b")
println(hashSet + "c")
import scala.collection.mutable.Map
val treasureMap = Map[Int, String]()
treasureMap += (1 -> "a")
println(treasureMap(1))

5. Learn to recognize the functional style

def printArgs(args: Array[String]): Unit = {
  args.foreach(println)
}
def printArgs(args: Array[String]): Unit = {
  for (arg <- args) 
    println(arg)
}
def formatArgs(args: Array[String]) = args.mkString("\n")

6. Read lines from a file

import scala.io.Source
if (args.length > 0 ) {
  for (line <- Source.fromFile(args(0)).getLines())
    println(line.length + " " + line)
} else 
  Console.err.println("Please enter filename")

val lines = Source.fromFile(args(0)).getLines().toList

7. File Operation

val filesHere = (new java.io.File(".")).listFiles
for (
  file <- filesHere 
  if file.isFile
  if file.getName.endsWith(".scala"))
  println(file)
def fileLines(file: java.io.File) = 
  scala.io.Source.fromFile(file).getLines().toList

def grep(pattern: String) =
  for {
    file <- filesHere
    if file.getName.endsWith(".scala")
    line <- fileLines(file)
    trimmed = line.trim
    if trimmed.matches(pattern)
  } println(file + ": " + trimmed)
val forLineLengths = 
  for {
    file <- filesHere
    if file.getName.startWith("hello")
    if file.getName.endsWith(".scala")
    line <- fileLines(file)
    trimmed = line.trim
    if trimmed.matches(".*for.*")
  } yield trimmed.length

8. String

println("""Welcome to Ultamix 3000. 
           Type "Help" for Help.""")
println("""|Welcome to Ultamix 3000.
           |Type "Help" for help.""".stripMargin)

9. Operators are methods

val s = "hello"
s indexOf 'o' 
s.indexOf('o')
s toLowerCase
s.toLowerCase

10. Exception handling with try expressions

import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
try {
  val f = new FileReader("input.txt")
} catch {
  case ex: FileNotFoundException =>
  case ex: IOException =>
}
import java.io.FileReader
val file = new FileReader("input.txt")
try {
} finally {
  file.close()
}

11. Placeholder syntax

someNumbers.filter(_ > 0)
val f = (_: Int) + (_: Int)

12. Simplify client code

Bad code:

def containsOdd(nums: List[Int]): Boolean = {
  var exists = false
  for (num <- nums)
    if (num % 2 == 1)
      exists = true
  exists
}

Good code:

def containsOdd(nums: List[Int]) = nums.exists(_ % 2 == 1)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s