Scala模式匹配&样例类&偏函数

2018-10-06  本文已影响0人  hipeer

模式匹配

样例类

abstract class Solution
case class Add(a: Int, b: Int) extends Solution
case class Mul(a: Int, b: Int) extends Solution
// 还可以有单例的样例对象
case object Nothing extends Solution

def getType(obj: Solution): Any = {
  obj match {
    case Add(a, b) => a + b
    case Mul(a, b) => a * b
    case Nothing => "Nothing"
    case _ => "Null"
  }
}

// 用法
val add = Add(1, 1)
val mul = Mul(10, 10)
val result = getType(add)  // 2
val result1 = getType(mul) // 100

// 可以把模式匹配直接放到公共超类中
abstract class Solution{
  def getType: Any = {
    this match {
      case Add(a, b) => a + b
      case Mul(a, b) => a * b
      case Nothing => "Nothing"
      case _ => "none"
    }
  }
}

// 用法
add.getType
mul.getType

注意: 样例类的实例使用(), 样例对象不使用()。

当声明一个样例类时会自动发生下面几件事:
密封类
sealed abstract class Solution
case class Add(a: Int, b: Int) extends Solution
case class Mul(a: Int, b: Int) extends Solution
模拟枚举

偏函数

// 定义
val fun: PartialFunction[Int, String] = { case 1 => "yes"; case 0 => "no" }

// 用法
fun(1)          // yes
fun(0)          // no
fun.isDefineAt(1)   // true
fun.isDefineAt(3)   // false
fun(3)          // 报错
"1+2*3-4" collect { case '+' => 1; case '*' => 2; case '-' => 1 }   // Vector(1, 2, 1)
react {
  case (name: String, actor: Actor) => {
    actor ! getip(name)
    act()
  }
  case msg => {
    println("UnHandler message" + msg)
    act()
  }
}

注意:偏函数表达式必须位于编译器可以推断出返回类型的上下文中。把它赋值给一个带有类型声明的变量,或者将它作为参数传递都是可以的。

上一篇下一篇

猜你喜欢

热点阅读