scala模式匹配


前言

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

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


内容匹配

e.g.

	//内容匹配:字符串:正则
	//这里先确定邮箱格式正确之后再确认邮箱类型
    val email = "796282767@qq.com"
    val rst = email match {
      case i if (i.matches("^\\w+@[0-9a-z]{2,10}\\.(com|qq|edu|org)$")) => i match {
        case i if (i.matches(".*@qq\\..*")) => Some("qq")
        case i if (i.matches(".*@163\\..*")) => Some("163")
        case i if (i.matches(".*@hotmail\\..*")) => Some("hotmail")
      }
      case i => None
    }
    println(rst)

e.g. result:

Some(qq)

类型匹配

e.g.

("a", true, 18, 20.22, 'b', 20L, 20.1f).productIterator.foreach(x => println(x match {
      case i: String => s"$i is a String"
      case i: Boolean => s"$i is a Boolean"
      case i: Int => s"$i is a Int"
      case i: Double => s"$i is a Double"
      case i: Char => s"$i is a Char"
      case i: Long => s"$i is a Long"
      case i: Float => s"$i is a Float"
    }))

e.g.result:

a is a String
true is a Boolean
18 is a Int
20.22 is a Double
b is a Char
20 is a Long
20.1 is a Float

结构匹配

e.g.

val products = Array((1, 2, 3), (1, (2, 3)), ((1, 2), 3))
    products.foreach(x => println(x match {
      case (a, b, c) => 'A'
      case ((a, b), c) => 'B'
      case (a, (b, c)) => 'C'
    }))

e.g.result:

A
C
B

内容匹配:数值区间

e.g.

var age = 20;
    val unit = age match {
      case i if (i >= 18) => "mature"
      case i => "raw"
    }
    println(unit)

e.g.result:

mature

原创作者:wsjslient

作者主页:https://blog.csdn.net/wsjslient


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值