scala基础语法-match模式匹配

来源:互联网 发布:什么是双向数据绑定 编辑:程序博客网 时间:2024/04/20 20:28
package org.xj.scala.spark


/**
 * 模式匹配
 */
class Basic5 {


}


//样例类,不可变性,val定义,不建议var ||-->常用于模式匹配
/**
 * case class(多用在匹模式匹配中)
 * 构造器中的每一个类型都为val,不建议使用var
 *   不用new就可以直接产生对象(为什么?apply方法)
 */
case class Book(name: String, author: String)


object Basic5 extends App {
  val value = 3
  val result = value match { //判断value值,返回值由下面判断结果确定
    case 1 => "one"
    case 2 => "two"
    case _ => "some other number" //如果什么都不是
  }


  val result2 = value match {
    case i if i == 1 => "one"
    case i if i == 2 => "two"
    case _ => "some othor number"
  }


  //  println("resule1 of match is:" + result)
  //  println("resule2 of match is:" + result2);


  //类型匹配
  def t(obj: Any) = obj match { //Any任何类型
    case x: Int => println("Int") //x代表传入的值
    case s: String => println("String") //s代表传入的值
    case _ => println("unknown type") //任何类型
  }


  //t("1")


  val macTalk = Book("xiaohua", "CJQ")
  macTalk match { //模式匹配macTalk的值
    case Book(name, author) => println("this is book")
    case _ => println("unknown")
  }
}
0 0