Scala学习笔记——样本类和模式匹配

1.样本类

在申明的类前面加上一个case修饰符,带有这种修饰符的类被称为样本类(case class)。

被申明为样本类的类的特点:1.会添加和类名一致的工厂方法;2.样本类参数列表中的所有参数隐式获得了val前缀,因此它被当做字段维护;3.编译器被这个样本类添加了toString、hashcode、equals方法的实现;4.支持了模式匹配

2.模式匹配

一个模式匹配包含了一系列备选项,每个都开始于关键字case。每个备选项都包含了一个模式及一到多个表达式,它们将在模式匹配过程中被计算。

其中箭头符号=>隔开了模式和表达式。

package com.scala.first

/**
  * Created by common on 17-4-19.
  */
object CaseClass {

  def main(args: Array[String]): Unit = {
    println(cal("+"))

    prtList(List(0, 1))

    println(prtType("abc"))
    println(prtType(Map(1 -> 1)))
  }

  def cal(exp: String): Int = {
    val add = "+"
    val result = 1
    exp match {
      case "+" => result + 2 //常量模式仅仅匹配自身
      case "-" => result - 2
      case "*" => result * 2
      case "/" => result / 2
      case add => result + 2 //变量模式可以匹配任意对象
      case _ => result //通配模式匹配任意对象
    }
  }

  //序列模式
  def prtList(list: List[Int]) = list match {
    case List(0, _, _) => println("this is a list") //序列模式,可以匹配List或者Array
    case List(1, _*) => println("this is a list, too") //匹配一个不指定长度的序列
    case _ => println("other")
  }

  //元组模式
  def prtTuple(tup: Any) = tup match {
    case (0, _, _) => println("this is a tuple") //元组模式
    case _ => println("other")
  }

  //类型模式,可以用在类型测试和类型转换
  def prtType(x: Any) = x match {
    case s: String => s.length
    case m: Map[_, _] => m.size
    case _ => 1
  }

}
原文地址:https://www.cnblogs.com/tonglin0325/p/6736416.html