如何比较元组值



我只是有一个快速的语法问题,我没有找到答案。例如,我有一个元组(2,3(,我想比较这些值。为了解决这个问题,我将其归结为一个特定的问题案例。

我尝试过这样做:

def isNumberOneBigger(tuple: Tuple): Boolean = tuple match {
      case tuple._1 > tuple._2 => true
}

它不起作用。当我使用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
}

如果没有匹配,它是:

def isNumberOneBigger(tuple: (Int,Int)): Boolean =
  tuple._1 > tuple._2

这对我来说似乎很好。

如果要继续使用模式匹配,可以编写以下代码

def isNumberOneBigger(tuple: (Int,Int)): Boolean ={
  tuple match {
    case x: (Int,Int)  if x._1 > x._2 => true
    case _ => false
  }
}

你可以做:

def isNumberOneBigger(tuple: (Int, Int)): Boolean = tuple match {
    case (a: Int, b:Int) if (a > b) => true
    case _ => false
}

注意添加case _ =>否则,您将获得MatchError异常。

你可以在这里"玩"一下

最新更新