Scala

Blogs:

Algorithmic challenge: http://dcsobral.blogspot.tw/search/label/programming

Code commit: http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-2

Daily scala: http://daily-scala.blogspot.tw/2009/08/creating-xml.html

Scala in short : http://rbsomeg.blogspot.tw/2013/01/scala-for-uninitiated-java-developer-22.html

===============================================================

Scala uses parentheses () to declare Array because there’s a set of declarations such as “def apply()" enabling Array access and modification. Thus we can write Array.apply(1,2,3)

================================================================

Few ways to make method calls:

> class Paws{ def getSymbol() = “P"}
> val a1 = new Paws
> println(a1.getSymbol)
> println(a1.getSymbol)
> println(a1 getSymbol)

================================================================

Write to File and reset

import java.io.{File,FileWriter}
import scala.io.Source
> val toFile1 = new FileWriter(“/tmp/daily-scala1″)
> val toFile2 = new FileWriter(“/tmp/daily-scala2″)
> val fromFile = Source.fromFile(“test.scala")
> try{toFile1.write(fromFile.getLines.mkString(“\n"))} finally {toFile.close}
> try{toFile2.write(fromFile.reset.getLines.mkString(“\n"))} finally {toFile.close}

================================================================

Class or Case classe

http://www.codecommit.com/blog/scala/case-classes-are-cool

  • Constructor parameters become public “fields” (Scala-style, which means that they really just have an associated accessor/mutator method pair)
  • Methods toString()equals() and hashCode() are defined based on the constructor fields
  • A companion object containing:
    • An apply() constructor based on the class constructor
    • An extractor based on constructor fields

> class aclass(aprivate: Int, val apublic: Int, var alsopublic)
> val instOfAclass = new aclass(1,2,3)
> insOfAclass.aprivate => fail #Becase it’s a private variable
> case caseclass(apublic: Int, val alsopublic: Int, var anotherpublic: Int)
> val instOfCaseClass = new (1,2,3)
> instOfCaseClass.c1 => 1 #All variables are public

==========================================================

One of the principle of Scala is to be deep not wide, which means the language attempts to apply a small set of rules in many different ways and situations. For instance, pattern matching.

================================================================

Tuples are light-weight way of grouping data in simple data object. (1, 1,2, ‘c’, “String",true) up to 22 elements and can be homogeneous and heterogeneous.

================================================================

Assignment and Parameter Objects

>  case class Name(first: String, middle: String, last: String)
> Name(“km","middle","chen") match {
> case data: Name => {val Name(f,m,l) = data; println(f)}
> km

================================================================

Pattern Matching

scala> val someobj: AnyRef  = “String" match {
| case _ : java.io.File => “File"
| case _ : String => “String"
| case _ : AnyRef => “AnyRef"
| }
res10: java.lang.String = String

================================================================

Implicit method

The ability to extend and existing class with new methods in a type safe manner. We can define implicit method which converts one object from one type to another type.

> class MyInteger (i: Int) { def inc = new MyInteger(i+1)}
> object Conversion {
> implicit def int2MyInteger(i: Int) = new MyInteger(i)
> implicit def myInt2Int(mI: MyInteger) = mI.i
> }
> def takesInt(i: Int) = println(i)
> takesInt(1.inc)
> 2

================================================================

Objects

Scala doesn’t have static methods the same way as Java does. Scala has “object" which is a singleton object. One difference is that object can extends abstract classes and traits. Object is referred to as modules as well which is a good way to modularize projects.

> object Sports {
>  case class Team (name: String)
> def print(teamName: Team) = println(teamName)
> object basketBall{ def team = Team(“Team name")
> }
> val aTata = Sports.basketBall.team
> Sports.print()
> Team name

================================================================

Named and Default Arguments

> def bigMethod(p1: Int = 1, p2: Int = 2, p3: Int = 3) = p1+p2+p3
> def bigMethod()    #Must provide ()
> 6
> bigMethod(10,10)
> 23
> bigMethod(p3 = 4, p2=4)
> 9

===============================================================

Apply and Update Methods

When we call “obj(param)", the call is translated by the compiler to “pbj.apply(param)". Similarly, “obj(param) = value" is compiled to “obj.update(param, value)". The update method can have many parameters but the last one is treated as a value.

scala> class Phonebook {
| val numbers = scala.collection.mutable.Map[String,String]()
| def apply(name: String) = numbers(name)
| def update(name: String, number: String) = numbers(name) = number
| }
> val book = new Phonebook()
> book(“km") = “1234567″
> print(book(“km"))
> 1234567

===============================================================

sealed trait can be extended only in the same file than its declaration.

===============================================================

Adding Methods in Trait

“self" type declares what type of class the trait can be applied to
If there is no “self" type then it is assumed to be type “Any".
We can instantiate a method which “takes class with trait" as the parameter types.
We can use the tail recursion as a for loop

  1. scala> trait Lines {
  2.      | // the self type declares what type of class the trait can be applied to
  3.      | // if there is no self type then it is assumed it can be applied to Any type
  4.      | self:java.io.Reader =>
  5.      | def nextLine:Option[String] = {
  6.      | val builder = new scala.collection.mutable.StringBuilder()
  7.      |
  8.      | var next = read()
  9.      |
  10.      | while( next != -1 && next.toByte.toChar != ’\n’ ){
  11.      | builder += next.toByte.toChar
  12.      | next = read()
  13.      | }
  14.      |
  15.      | if( builder.isEmpty ) None
  16.      | else Some(builder.toString)
  17.      | }
  18.      | }
  19. defined trait Lines
  20. // Strings starting and ending with (“"") are called raw strings.  All characters
  21. // within """ """ are automatically escaped.
  22. // I am creating a reader and mixing in the Lines trait on construction
  23. scala> val reader = new java.io.StringReader( """line one
  24.      | line two""" with Lines
  25. reader: java.io.StringReader with Lines = $anon$1@3850620f
  26. scala> reader.nextLine
  27. res0: Option[String] = Some(line one)
  28. scala> reader.nextLine
  29. res1: Option[String] = Some(line two)
  30. scala> reader.nextLine
  31. res2: Option[String] = None
  32. scala> reader.nextLine
  33. res3: Option[String] = None
  34. // we can define a method that takes a reader with lines
  35. scala> def toCollection( reader:java.io.StringReader with Lines) = {
  36.      | def collect:List[String] = reader.nextLine match {
  37.      |   case None => Nil
  38.      |    // we do not need to worry about stack overflow
  39.      |    // because of tail recursion.  This method cannot be
  40.      |    // extended and collect is the last like in the collect
  41.      |    // method so this method will be transformed into a loop
  42.      |   case Some( line ) => line :: collect
  43.      | }
  44.      |
  45.      | collect
  46.      | }
  47. toCollection: (reader: java.io.StringReader with Lines)List[String]
  48. scala> toCollection( new java.io.StringReader( "line one\nlinetwo" ) with Lines).size
  49. res8: Int = 2
  50. =============================================================
  51. Exception Handling
  52. def handle(h: => Unit) = {
    | try {h} catch {
    | case _: AssertionError => println(“Whoops an assertion error")
    | case r: RuntimeException => println(“Runtime Exception “+r.getStackTraceString)
    | case e if(e.getMessage == null) => println(“Unknow exception with no message")
    | case e => println(“An unknown message"+e.getMessage)
    | }
    | }
  53. ===========================================================
  54. FoldLeft and FoldRight
  55. API: def foldLeft[B](z: B)(f: (B, A) ⇒ B): B
  56. FoldLeft and FoldRight take a “result" parameter (B), an element (A) and starting index (z)
  57. We can use “case" instead of function as parameter to foldLeft and foldRight
  58. > val m = Map(1 -> “one", 2 -> “two", 3 -> “three")

================================================================

Currying

Simplify multiple arguments

http://www.jayconrod.com/posts/14/currying-and-why-we-dont-pass-arguments-as-tuples

================================================================

Partial Functionhttp://blog.bruchez.name/2011/10/scala-partial-functions-without-phd.html

================================================================

Save to file one liner : 

Some(new PrintWriter(“filename")).foreach{p => p.write(“hello world"); p.close}

================================================================

Functional Dependency : http://www.chuusai.com/2011/07/16/fundeps-in-scala/

================================================================

Advanced implicit : http://yz.mit.edu/wp/true-scala-complexity/

廣告
本篇發表於 Uncategorized。將永久鏈結加入書籤。

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s