我只有一个快速的语法问题,但找不到答案。我有一个元组,例如(2,3),我想比较那些值。为了解决这个问题,我将其归结为一个关于该问题的特定案例。
我试图这样做:
def isNumberOneBigger(tuple: Tuple): Boolean = tuple match {
case tuple._1 > tuple._2 => true
}
Run Code Online (Sandbox Code Playgroud)
没用 当我使用compareTo或类似的建议时,总是出现错误。由于我的代码更长,更复杂,所以我不能只使用if-else。模式匹配很有意义。有人知道吗?感觉很简单,但我是Scala的新手。
这是两个基于匹配的解决方案:
def isNumberOneBigger(tuple: (Int,Int)): Boolean = tuple match {
case (x1, x2) => x1 > x2
}
def isNumberOneBigger(tuple: (Int,Int)): Boolean = {
val (x1, x2) = tuple
x1 > x2
}
Run Code Online (Sandbox Code Playgroud)
没有匹配的是:
def isNumberOneBigger(tuple: (Int,Int)): Boolean =
tuple._1 > tuple._2
Run Code Online (Sandbox Code Playgroud)
在我看来,这很好。
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |