2025/1/31


Scala的高阶特性包括高阶函数、闭包、模式匹配和案例类。这些特性使得Scala在处理复杂逻辑时更加灵活和强大。
高阶函数:函数可以作为参数或返回值。
模式匹配:强大的模式匹配机制,用于替代if-else或switch-case。
案例类:用于模式匹配的类。

 

// 高阶函数
def applyFunction(f: Int => Int, x: Int): Int = {
f(x)
}

val double = (x: Int) => x * 2
println("Apply double function: " + applyFunction(double, 5)) // 输出:10

// 模式匹配
def matchExample(x: Any): String = x match {
case 1 => "One"
case "hello" => "Hello"
case _ => "Unknown"
}

println(matchExample(1)) // 输出:One
println(matchExample("hello")) // 输出:Hello
println(matchExample(10)) // 输出:Unknown

// 案例类
case class Person(name: String, age: Int)

val person = Person("Alice", 25)
person match {
case Person(name, age) => println(s"Name: $name, Age: $age")
}

 

运行步骤:
在src/main/scala/目录下创建一个文件,例如AdvancedFeatures.scala。
将上述代码粘贴到文件中。
在项目根目录下运行:

sbt run
观察输出结果。

Scala的高阶函数和模式匹配是其强大的特性之一。通过这些特性,可以编写出更灵活和高效的代码。

posted @ 2025-01-31 13:49  伐木工熊大  阅读(9)  评论(0)    收藏  举报