code snippet(scala always to be continue...)
Posted satyrs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了code snippet(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 [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...)的主要内容,如果未能解决你的问题,请参考以下文章