【问题标题】:Scala pattern matching double curly bracketsScala模式匹配双花括号
【发布时间】:2016-08-27 20:51:27
【问题描述】:

我不确定这可能是 Scala 模式匹配问题。我看到了以下示例,它使用了 Scala 模式匹配。

def sum(ints: List[int]): Int = ints match {
  case Nil => 0
}

def sum(ints: List[int]): Int {
  ints match {
    case Nil => 0
  }
}

这两个例子有什么区别?

谢谢你:)

【问题讨论】:

标签: scala pattern-matching brackets


【解决方案1】:

在 Scala 中,如果您将模式匹配作为函数内的第一个表达式,您可以用两种方式编写语法,但它们是等价的。

注意:这里我们直接从模式匹配开始:

def toInt(optStr: Option[String]): Option[Int] = optStr match {
 case Some(str) = Some(str.toInt)
 case None =>  None
}

另一种说法是,你在多行括号内做同样的事情

 def toInt(optStr: Option[String]): Option[Int] = {
  //same pattern matching inside multiline brackets
  optStr match {
    case Some(str) = Some(str.toInt)
    case None => None
  }

}

【讨论】:

  • 为了清楚起见,“如果您将模式匹配作为函数内的 only 表达式进行,您可以编写...”和当然,这适用于任何其他表达式。
  • @grzesiekw 是的!这适用于任何单个表达式。如果它有多个表达式,您需要使用 {}。
【解决方案2】:

花括号是 Scala 用来将一组表达式粘合在一起的方式,其结果是块中最后一个表达式的结果。

例如:

{
    val x = 3
    x*2
}

是一个表达式,其结果为6

在花括号中编写单个表达式是多余的,仅出于审美目的才有意义。

回到你的模式匹配:

ints match {
  case Nil => 0
}

与其他表达式一样,您可以将其写在花括号内,也可以不写。

{
    ints match {
      case Nil => 0
    }
}

Scala 允许您将方法体定义为一组表达式:

def methodName(params...) { exp0; exp1; .., resExp } // Return type will be Unit.

注意 Scala 的类型推断将确定 methodName 返回类型为 Unit

或者像=,右边有一个表达式,也可以是一组用大括号粘合的表达式。

def methodName(params...): Type = expression
def methodName(params...) = expression //Return type will be the expression's type.

所以你可以写成这三种形式:

// `=` with a single expression at is right side.
def sum(ints: List[Int]): Int = ints match {
  case Nil => 0
}

// `=` with a glued sequence of expressions at is right side.
def sum(ints: List[Int]): Int = {
    ints match {
      case Nil => 0
    }
}

// A glued sequence of expressions at is right side, but its return type will be Unit!
def sum(ints: List[Int]) {
    ints match {
      case Nil => 0
    }
}

【讨论】:

  • 感谢 Pablo 的详细解答!我的好奇心肯定消失了。
猜你喜欢
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多