scala 学习笔记七 基于类型的模式匹配

  1、介绍

    Scala 提供了强大的模式匹配机制,应用也非常广泛。

    一个模式匹配包含了一系列备选项,每个都开始于关键字 case。每个备选项都包含了一个模式及一到多个表达式。箭头符号 => 隔开了模式和表达式。

    先看一个整型值模式匹配的例子

    

    match 对应 Java 里的 switch,但是写在选择器表达式之后。即: 选择器 match {备选项}。

 

  2、基于类型的模式匹配

 

    

    acceptAnything的参数类型Any允许任何类型的参数,如果向某个方法传递的类型具有多样性,并且没有任何共性部分,那么Any就可以解决此问题。

 

    其它例子

  case class Person(name:String, age:Int,phone:String){
  }
  def acceptAnything(x:Any):String = {
    x match {
      case s:String => "A string:" +s
      case i:Int if(i < 20) => s"An Int less than 20:$i"
      case p:Person => s"A person ${p.name}"
      case _ => "Unkown"
    }
  }

  def plus1(x:Any):Any ={
    x match {
      case s:String => s
      case i:Int =>i
      case p:Person =>p.name
      case _ => "unkown"
    }
  }

  def convertToSize(x:Any):Any={
    x match {
      case i:Int => i
      case s:String => s.length
      case f:Float => f
      case p:Person =>1
      case v:Vector[Int] =>v.length
      case _ => 0
    }
  }

  def convertToSize1(x:Any)={
    x match {
      case i:Int => i
      case s:String => s.length
      case f:Float => math.round(f)
      case p:Person =>1
      case v:Vector[Int] =>v.length
      case _ => 0
    }
  }

  def forecast(i:Int)={
    i match {
      case i if(i>=100) => "Sunny"
      case i if(i>=80) => "Mostly Sunny"
      case i if(i>=50) => "Partly Sunny"
      case i if(i>=20) => "Cloudy"
      case i if(i>0) => " most Cloudy"
      case _ => " unkown"
    }
  }
  def main(args: Array[String]): Unit = {

    val v = forecast(-1)
    println(v)
    //输出:5
    
    val v2 = forecast(90)
    println(v2)
    //输出:11

    val v3 = forecast(60)
    println(v3)
    //输出:2

    val v4 = forecast(30)
    println(v4)
    //输出:0
  }

 

posted on 2018-07-24 16:36  shaomine  阅读(222)  评论(0编辑  收藏  举报