Scala 模式匹配

2022-05-13 14:44 更新

模式匹配允许我们在多个条件之间进行编程选择。

例子

object Main extends App {
    def printNum(int: Int) {
     int match {
         case 0 => println("Zero")
         case 1 => println("One")
         case _ => println("more than one")
     }
    }
    printNum(0)
    printNum(1)
    printNum(2)
}

带下划线_的最后一种情况是通配符。它匹配任何未定义在上面的情况下。

以下代码说明计算Fibonacci数字的示例。

def fibonacci(in: Int): Int = in match {
 case 0 => 0
 case 1 => 1
 case n => fibonacci(n - 1) + fibonacci(n - 2)
}

Scala允许将守卫放置在模式中,以测试无法在模式声明本身中测试的特定条件。

因此,如果传递负数,我们可以写入我们的Fibonacci 计算器返回0,如以下示例所示。

def fib2(in: Int): Int = in match {
 case n if n <= 0 => 0
 case 1 => 1
 case n => fib2(n - 1) + fib2(n - 2)
}

匹配任何类型

让我们考虑一个任何类型的元素的列表,包含一个String,一个Double,一个Int和一个Char。

object Main extends App {
    val anyList= List(1, "A", 2, 2.5, 'a')

    for (m <- anyList) {
        m match {
            case i: Int => println("Integer: " + i)
            case s: String => println("String: " + s)
            case f: Double => println("Double: " + f)
            case other => println("other: " + other)
        }
    }
}

测试数据类型

下面的方法测试一个传入的Object,看看它是一个String,一个Integer,或者别的东西。

def test2(in: Any) = in match {
    case s: String => "String, length "+s.length
    case i: Int if i > 0 => "Natural Int"
    case i: Int => "Another Int"
    case a: AnyRef => a.getClass.getName
    case _ => "null"
}
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号