scala 模式匹配之Type、Array、List和Tuple

本文深入探讨Scala编程中模式匹配的应用,重点解析如何针对Type、Array、List和Tuple进行有效匹配,通过实例代码展示其用法和技巧。
摘要由CSDN通过智能技术生成

1、代码

package com.yy.base

/**
 * Scala 模式匹配
 * Type Array List Tuple
 */
object PatternMatchMore extends App {
  
    println("-----Type模式匹配------")
    def typeMatch(t:Any) = t match{
      case c:Int => println(c+"是个整数")
      case c:String => println(c+"是个字符串")
      case m:Map[_,_] => m.foreach(println)
      case _ => println("没有匹配上")
    }
  //调用
    typeMatch(2)
    typeMatch("scala")
    typeMatch(Map("name"->"yy"))
    
    println("-----Array模式匹配------")
    def arrayMatch(arr:Any) = arr match{
      case Array(0) => println("Array是一个元素为0的数组")
      case Array(x,y) => println("Array有两个元素:" + x +","+y)
      case Array(0,_*) => println("Array至少有一个元素,且第一个元素为0")
      case _ => println("其他类型的数组")
    }
    arrayMatch(Array(0))
    arrayMatch(Array(0,1))
    arrayMatch(Array(0,1,2,3,4,5))
    arrayMatch(Array(1,2,3,4,5))
    
    println("-----List模式匹配------")
    def listMatch(list:Any) = list match{
      case 0::Nil => println("List:0")
      case x::y::Nil => println("List:" + x + "," + y)
      case 0::tail => println("List:0......")
      case _ => println("其他类型的List")
    }
    listMatch(List(0))
    listMatch(List(1,2))
    listMatch(List(0,1,2,3,4,5))
    listMatch(List(1,2,3,4,5))
    
    println("-----Tuple模式匹配------")
    def tupleMatch(t:Any) = t match{
      case (0,_) => println("Tuple start with 0")
      case (x,0) => println("Tuple start with " + x)
      case _ => println("其他类型的Tuple")
    }
    tupleMatch((0,"yy"))
    tupleMatch(("xx",0))
    tupleMatch((0,1,2,3))
}
2、结果

-----Type模式匹配------
2是个整数
scala是个字符串
(name,yy)
-----Array模式匹配------
Array是一个元素为0的数组
Array有两个元素:0,1
Array至少有一个元素,且第一个元素为0
其他类型的数组
-----List模式匹配------
List:0
List:1,2
List:0......
其他类型的List
-----Tuple模式匹配------
Tuple start with 0
Tuple start with xx
其他类型的Tuple

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值