code snippet-02(scala always to be continue...)
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 c@Calculator(_, _) => "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 }
7PartialFunction
val sample = 1 to 10 val isEven: PartialFunction[Int, String] = { case x if x % 2 == 0 => x+" is even" } // the method collect can use isDefinedAt to select which members to collect val evenNumbers = sample collect isEven val isOdd: PartialFunction[Int, String] = { case x if x % 2 == 1 => x+" is odd" } // the method orElse allows chaining another partial function to handle // input outside the declared domain val numbers = sample map (isEven orElse isOdd)
8
From satrys,
Kristen wang
浙公网安备 33010602011771号