Scala 中的下划线占位符
Mohammad Irfan 2023年1月30日 Scala Scala Underscore
- 在 Scala 中使用下划线导入语句
- 在 Scala 的
for循环中使用下划线 - 在 Scala 的 case 模式中使用下划线
- 在 Scala 的变量中使用下划线
- 在 Scala 中使用下划线数值
本教程将讨论下划线 (_) 及其在 Scala 中的用法。在 Scala 中,下划线 (_) 是一个占位符,表示没有值或变量。
我们可以使用它为变量分配默认值,并在代码中导入包的所有类。
在 Scala 中使用下划线导入语句
使用下划线来导入包是 Scala 中占位符的常见用法。例如,如果我们要导入所有的中断函数,请使用下划线。
import scala.util.control.Breaks._ object MyClass { def main(args: Array[String]) { breakable { for(i<-1 to 10 by 2){ if(i==5) break else println(i) } } } } 输出:
1 3 在 Scala 的 for 循环中使用下划线
我们使用 foreach 中的下划线来遍历列表元素。我们用它来代替列表的任何引用变量。
object MyClass { def main(args: Array[String]) { List(1,2,3,4).foreach(println(_)) } } 输出:
1 2 3 4 在 Scala 的 case 模式中使用下划线
我们还可以使用它在 case 模式中设置默认 case。在其他语言中,我们使用 default 关键字来定义一个在没有找到匹配 case 时执行的默认 case,在 Scala 中也是如此。
object MyClass { def matchTest(x: Int): String = x match { case 1 => "one" case 2 => "two" case _ => "anything other than one and two" } def main(args: Array[String]) { val r = matchTest(2) val r2 = matchTest(20) println(r) print(r2) } } 输出:
two anything other than one and two 在 Scala 的变量中使用下划线
我们可以使用下划线来引用变量声明中的默认值。如下例所示,我们声明了一个默认值为 0 的整型变量。
object MyClass { var i: Int = _ def main(args: Array[String]) { print(i) } } 输出:
0 在 Scala 中使用下划线数值
这是使用下划线的另一种情况。我们正在使用它来使数值更具可读性。
当我们有一个很大的值时,读取一次并不容易。它也称为数字分隔符。
object MyClass { def main(args: Array[String]) { var i: Int = 1_000_000 print(i) } } 输出:
1000000 Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe