Monthly Archives: December 2014

Scala (19): Lazy

lazy means it only be initialized for the first visit, not when its class is initialized. lazy is suitable for some scenario, for example, the cost time on initializing is very long.

Here is an example to get Scala version number from github.

class ScalaCurrentVersion(val url: String) {
  lazy val source = {
    println("fetching from url...")
    scala.io.Source.fromURL(url).getLines().toList
  }
  lazy val majorVersion = source.find(_.contains("version.major"))
  lazy val minorVersion = source.find(_.contains("version.minor"))
}
Advertisements

Scala (18): Tail Recursive

Tail recursive is one kind of recursive, which will call itself at the end of the function. Scala compiler will do some optimization on tail recursive in order to avoid stack overflow on recursive.

Here we use an example to implement foldLeft by tail recursive method.

val file = List("warn 2013 msg", "warn 2012 msg", "error 2013 msg", "warn 2013 msg")

def wordcount(str: String): Int = str.split(" ").count("msg" == _)

def foldLeft(list: List[Int])(init: Int)(f: (Int, Int) => Int): Int = {
  list match {
    case List() => init
    case head :: tail => foldLeft(tail)(f(init, head))(f)
  }
}

val num = foldLeft(file.map(wordcount))(0)(_ + _)

println(num) //output: 4