scala的模式匹配

Scala的模式匹配主要关键字为:match和case

匹配变量

var  str:String = "Hello World"
str(7) match{
	case 'a' =>println("This is a")
	case 'b' =>println("This is b")
	case 'W' =>println("This is W")
	// _表示其他情况
	case _ =>println("This is a")
}

匹配数组

var myArray = Array(1,2,3,4)
myArray match {
	//数组无元素
	case Array(0) => println("0")
	//数组包含两个元素
	case Array(x,y) => println("数组包含两个元素,和为:"+(x+y))
	//数组包含3个元素
	case Array(x,y.z) => println("数组包含两个元素,和为:"+(x+y+z))
	//数组其余情况
	case Array(x,_*) => println("myArray是一个数组")
}

样本类
如果我们想判断一个对象是否是某个类的对象,跟Java一样可以使用isInstanceOf

class Fruit
case class Apple(name:String) extends Fruit
case class Banana(name:String) extends Fruit
object Fruit1{
  def main(args: Array[String]): Unit = {
    var aApple:Fruit = new Apple("苹果")
    aApple match {
      case Apple(name) => println("这是:"+name)
      case Banana(name) => println("这是:"+name)
      case _ => println("其他水果")
    }
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值