Scala模式与元组类型匹配

时间:2018-11-16 22:33:29

标签: scala pattern-matching tuples

以下方法抛出错误,甚至没有调用它。

type Checklist = (Int,String,Boolean)
  def higherthan(a: Checklist,b:Checklist) : Boolean = (a._1,b._1) match {
    case a._1 >= b._1 => true
    case a._1 < b._1 => false
    case _ => false
}

错误如下:

Error:(3, 14) not found: value >=case a._1 >= b._1 => true

是否不可能从模式匹配中访问元组的元素?我想检查清单的前几个元素中哪个更大。对不起,有任何错误,英语不是我的母语,我是大一学生。

1 个答案:

答案 0 :(得分:4)

有几种方法:

def higherthan(a: Checklist, b: Checklist) : Boolean = (a , b) match {
  case (x, y) if x._1 >= y._1 => true
  case _ => false
}

def higherthan(a: Checklist, b: Checklist) : Boolean = (a , b) match {
  case ((x, _, _), (y, _, _)) if x >= y => true
  case _ => false
}

def higherthan(a: Checklist, b: Checklist) : Boolean = a._1 >= b._1

希望其中一种帮助。

相关问题