1. 程式人生 > >code snippet(scala always to be continue...)

code snippet(scala always to be continue...)

es6 ole map numbers 元組 oca lean ply mat

1() 有無問題

class foo{}
class foof{ def apply() = 2}

val nf = new foo
val nf =new foo()
val nff = new foof()// no difference, call apply
//無參的時候()有無都可

2extends同樣可接表達式

class AddOne extends (Int => Int) {
  def apply(m: Int): Int = m + 1
}

3樣本類的模型/類成員匹配

scala> case class Calculator(brand: String, model: String)
defined 
class Calculator scala> val hp20b = Calculator("HP", "20b") hp20b: Calculator = Calculator(hp,20b) scala> val hp20B = Calculator("HP", "20b") hp20B: Calculator = Calculator(hp,20b) scala> hp20b == hp20B res6: Boolean = true def calcType(calc: Calculator) = calc match { case Calculator("HP", "20B") => "financial" case
Calculator("HP", "48G") => "scientific" case Calculator("HP", "30B") => "business" case Calculator(ourBrand, ourModel) => "Calculator: %s %s is of unknown type".format(ourBrand, ourModel) case Calculator(_, _) => "Calculator of unknown type" case [email protected](_, _) => "Calculator: %s of unknown type".format(c) }

4面向表達式的異常

val result: Int = try {
  remoteCalculatorService.add(1, 2)
} catch {
  case e: ServerIsDownException => {
    log.error(e, "the remote calculator service is unavailable. should have kept your trusty HP.")
    0
  }
} finally {
  remoteCalculatorService.close()
}

5元組

scala> val hostPort = ("localhost", 80)
hostPort: (String, Int) = (localhost, 80)

scala> hostPort._1
res0: String = localhost

scala> hostPort._2
res1: Int = 80

scala> 1 -> 2
res0: (Int, Int) = (1,2)//創建兩個元素的tuple特殊語法

6Option中get/getOrElse

trait Option[T] {
  def isDefined: Boolean
  def get: T
  def getOrElse(t: T): T
}

scala> val numbers = Map("one" -> 1, "two" -> 2)
numbers: scala.collection.immutable.Map[java.lang.String,Int] = Map(one -> 1, two -> 2)

numbers.get("two").getOrElse(0)*2

val result = if (res1.isDefined) {
  res1.get * 2
} else {
  0
}

val result = res1 match {
  case Some(n) => n * 2
  case None => 0
}

code snippet(scala always to be continue...)