zoukankan      html  css  js  c++  java
  • Scala中的match(模式匹配)

    文章来自:http://www.cnblogs.com/hark0623/p/4196261.html   转载请注明

    代码如下:

    /**
     * 模式匹配
     */
    case class Class1(param1: String, param2: String)
    
    case class Class2(param1: String)
    
    object Case {
      def main(args: Array[String]) {
        //通过模式匹配进行条件判断
        val test1: String = "1"
        val result1 = test1 match {
          case "1" => {
            "one"
          }
          case "2" => "two"
          case _ => "other"
        }
        println(result1)
    
        //通过模式匹配进行条件判断,可自定义条件
        val test2: Int = 1;
        val result2 = test2 match {
          case i if i + 1 == 2 => "one"
          case i if i + 1 == 3 => "tow"
          case _ => "error"
        }
        println(result2)
    
        //通过模式匹配进行类型条件判断
        val t3 = 1
        println(Test3(t3))
    
        //通过模式匹配进行类型条件判断
        val t4 = "1"
        println(Test3((t4)))
    
        //通过模式匹配进行类的判断与执行
        val test5 = Class1("1", "2")
        ClassMatch(test5)
    
        val test6 = Class2("3")
        ClassMatch(test6)
      }
    
      def ClassMatch(classTest: Any): Unit = {
        classTest match {
          case Class1(param1, param2) => {
            println("Class1:" + param1 + "_" + param2)
          }
          case Class2(param1) => {
            println("Class2:" + param1)
          }
          case _ => println("error")
        }
      }
    
      def Test3(data: Any): String = {
        data match {
          case x: Int => "Int"
          case x: String => "String"
          case _ => "unkown"
        }
      }
    }

    输出如下:

    one
    one
    Int
    String
    Class1:1_2
    Class2:3
  • 相关阅读:
    个人总结---小水长流,则能穿石
    软件工程与UML作业3(互评作业)
    软件工程与UML作业2
    软件工程与UML作业1
    大创省级答辩总结
    C语言知识汇编
    C语言知识点汇集
    C语言汇总3
    C语言汇总2
    c语言汇总1
  • 原文地址:https://www.cnblogs.com/hark0623/p/4196261.html
Copyright © 2011-2022 走看看