0 => y * 2 _ => -1 } -6ren">
gpt4 book ai didi

scala - 将 "case"关键字添加到 Scala 背后的原因是什么?

转载 作者:行者123 更新时间:2023-12-04 00:19:26 33 4
gpt4 key购买 nike

除了:

case class A

... 案例哪个很有用?

为什么我们需要使用 casematch ?不会:
x match {
y if y > 0 => y * 2
_ => -1
}

... 是 更漂亮更简洁?

或者为什么我们需要使用 case当一个函数接受一个元组时?说,我们有:
val z = List((1, -1), (2, -2), (3, -3)).zipWithIndex

现在,不是:
z map { case ((a, b), i) => a + b + i }

......比仅仅丑陋的方式:
z map (((a, b), i) => a + b + i)

……?

最佳答案

首先,正如我们所知,可以为同一个 case 场景放置多个语句,而无需一些分隔符号,只需一行跳转,例如:

x match {
case y if y > 0 => y * 2
println("test")
println("test2") // these 3 statements belong to the same "case"
}

case不需要,编译器必须找到一种方法来知道下一个案例场景何时关注一行。

例如:
x match {
y if y > 0 => y * 2
_ => -1
}

编译器如何知道 _ => -1属于第一种情况还是代表下一种情况?

而且,编译器怎么会知道 =>符号不代表文字函数,而是当前 case 的实际代码?

编译器肯定需要这样的代码来允许案例隔离:
(使用花括号或其他任何东西)
x match {
{y if y > 0 => y * 2}
{_ => -1} // confusing with literal function notation
}

当然,使用 case 的解决方案(目前由 scala 提供)关键字比在我的示例中使用花括号等某种分隔方式更具可读性和可理解性。

关于scala - 将 "case"关键字添加到 Scala 背后的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19471695/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com