Scala 基本语法

函数和方法

scala> class C {
     |   var acc = 0
     |   def minc = { acc += 1 }
     |   val finc = { () => acc += 1 }
     | }
defined class C

scala> val c = new C
c: C = C@1af1bd6

scala> c.minc // calls c.minc()

scala> c.finc // returns the function as a value:
res2: () => Unit = <function0>

abstract class

  • 不能实例化抽象类

    scala> abstract class Shape{
    |   def getArea():Int
    | }
    defined class Shape
    

Traits

trait Car {
  val brand: String
}

trait Shiny {
  val shineRefraction: Int
}
class BMW extends Car {
  val brand = "BMW"
}

class BMW extends Car with Shiny {
  val brand = "BMW"
  val shineRefraction = 12
}
  • 优先使用特质。一个类扩展多个特质是很方便的,但却只能扩展一个抽象类。

  • 如果你需要构造函数参数,使用抽象类。因为抽象类可以定义带参数的构造函数,而特质不行。例如,你不能说trait t(i: Int) {},参数i是非法的。

Object

Scala classes cannot have static variables or methods. Instead a Scala class can have what is called a singleton object, or sometime a companion object.

scala> class Bar(foo: String)
defined class Bar

scala> object Bar{
     |   def apply(foo: String) = new Bar(foo)
     | }

apply 方法,语法糖

scala> class Foo{}
defined class Foo

scala> object FooMaker{}
defined object FooMaker

scala> object FooMaker{
     |   def apply() = new Foo
     | }
defined object FooMaker

scala> val newFoo = FooMaker()
newFoo: Foo = Foo@229cb4d8

函数即对象

函数是Function*特质的示例,并且定义了apply语法糖

scala> object addOne extends Function1[Int, Int]{
     |   def apply(m: Int): Int = m + 1
     | }
defined object addOne

scala> addOne(1)
res0: Int = 2

case class

It makes only sense to define case classes if pattern matching is used to decompose data structures.

  • 实例化可以不加关键词new

  • toString更漂亮

  • 默认实现equals和hashCode

  • 默认序列化

模式匹配

  • 基本用法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    scala> val times = 1
    times: Int = 1

    scala> times match{
    | case 1 => "one"
    | case 2 => "two"
    | case _ => "other"
    | }
    res2: String = one
  • 带if守卫

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    scala> val score = 70
    score: Int = 70

    scala> score match{
    | case s if (score >= 90) => "优秀"
    | case s if (score >= 70) => "良好"
    | case s if (score >= 60) => "及格"
    | case _ => "不及格"
    | }
    res5: String = 良好
  • 类型的模式匹配

    1
    2
    3
    4
    5
    6
    7
    8
    try{
    something
    }catch{
    case e: IllegalArgumentException=> do something
    case e: FileNotFoundException=> do something
    case e: IOException => do something
    case _: Exception => do something
    }
  • case class的模式匹配

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    class Customer
    case class PersonalUser(name:String) extends Customer
    case class EnterpriseUser(name:String) extends Customer
    case class VipUser(name:String) extends Customer
    ...

    def service(c:Customer):Unit={
    c match{
    case EnterpriseUser(_)=>print("Enterprise")
    case PersonalUser(_)=>print("Personal")
    case VipUser(_)=>print("Vip")
    case _ =>print("None")
    }
    }
  • Option的模式匹配

    Some and None are both children of Option

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    def toInt(in: String): Option[Int] = {
    try {
    Some(Integer.parseInt(in.trim))
    } catch {
    case e: NumberFormatException => None
    }
    }

    toInt(someString) match {
    case Some(i) => println(i)
    case None => println("That didn't work.")
    }