scala学习笔记之模式匹配

Scala 模式匹配相当于java的switch,但是不需要break关键字。scala匹配到对应的值会立即退出,
模式匹配可用于替换java中的instance of

object PackageDemo extends App{
  var x= 1
  val result = x match{
    case 1 => "one"
    case 2 => "two"
    case 3 => "three"
    case _ => "other"
  }
 // println(result)  结果 one  
  var result2 = x match{//另一种方式
    case i if i==1 => "one"
    case i if i==2 => "two"
    case i if i==3 => "three"
    case _ => "other"
  }
 // println(result2)   结果 one
  def paramType(obj :Any) = obj match{
    case 1 => 1                  //匹配到int 1
    case "one" => "one"          //匹配到String 1
    case x : Int =>"Int"        //匹配到Int
    case x : String =>"String"  //匹配到String
    case _ => "obj"              //匹配所有
  }
  println(paramType(1))
  println(paramType("one"))
  println(paramType("StringParam"))
  println(paramType(null))}

结果:

1
one
String
obj

case class
1.构造器默认是val,不建议用var
2.实例不用new因为apply

case class Book(name:String,author:String){//构造器默认是val,不建议用var

}
object Book{
 val bookMatch = Book("呐喊","鲁迅")
  bookMatch match{
    case Book(name,author) => println("this is a book instance")
    case _ => println("this is not a book instance")
  }}

输出结果

this is a book instance
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值