scala 类错误:递归方法printExpr 需要结果类型 [英] Error on scala class : recursive method printExpr needs result type

查看:41
本文介绍了scala 类错误:递归方法printExpr 需要结果类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上遇到错误:

case Sum(l, r) => printExpr(l); print("+"); printExpr(r)

错误是:

递归方法printExpr需要结果类型

recursive method printExpr needs result type

这段代码对我来说没问题,我做错了什么?

This code looks ok to me, what am I doing wrong ?

abstract class Expr {

  case class Num(n: Int) extends Expr
  case class Sum(l: Expr , r: Expr) extends Expr
  case class Prod(l: Expr, r: Expr) extends Expr

  def evalExpr(e: Expr): Int = e match {
    case Num(n) => n
    case Sum(l, r) => evalExpr(l) + evalExpr(r)
    case Prod(l, r) => evalExpr(l) * evalExpr(r)
  }

  def printExpr(e: Expr) = e match {
    case Num(n) => print(" " + n + " ")
    case Sum(l, r) => printExpr(l); print("+"); printExpr(r)
    case Prod(l, r) => printExpr(l); print("x"); printExpr(r)
  }
}

推荐答案

Scala 中的递归方法需要明确声明的返回类型,如错误消息所述.

Recursive methods in Scala need an explicitly stated return type, as the error message states.

原因是 Scala 从方法体中使用的类型推断方法的返回类型.当方法的返回类型影响方法体中使用的类型(因为它递归地调用自己)时,Scala 无法确定它应该分配给方法的类型,因此它要求您在源代码中执行此操作(就像使用 evalExpr 一样,您在其中明确表示它返回 Int).

The reason is that Scala infers the method's return type from the types used in the method body. When the method's return type affects the types used in the method body (because it calls itself recursively), Scala isn't able to figure out what type it should assign to the method, so it requires that you do so in the source code (as you have with evalExpr, where you explicitly said that it returns an Int).

在这种情况下,您希望 printExpr 具有返回类型 Unit,这是没有信息的无趣值的类型.通常调用返回类型为Unit的方法只是为了它的副作用(比如print).

In this case, you want printExpr to have return type Unit, which is the type of uninteresting values with no information. Usually calling a method with return type Unit is only done for its side effects (such as print).

所以你可以把printExpr的标题行改成:

So you can change the header line of printExpr to:

def printExpr(e: Expr) : Unit = e match {

或者,Scala 有一些语法糖来声明过程".您可以将过程"视为不返回任何内容,而只是执行一些代码,但实际上 Scala 中的每个方法都返回something;过程"只是返回类型 Unit 的方法.这样做的语法是省略方法头后面的 =,但是你必须用大括号包围方法体(即使它是一个单一的表达式,就像你的匹配).所以你可以这样做:

Alternatively, Scala has some syntactic sugar for declaring "procedures". You can think of a "procedure" as not returning anything, and just executing some code, but really every method in Scala returns something; "procedures" are just methods that return type Unit. The syntax for doing so is to omit the = after the method's header, but then you must surround the method body with curly braces (even if it's a single expression, like your match). So you could do:

def printExpr(e: Expr) {
  e match {
    ...
  }
}

避免显式声明Unit.

这篇关于scala 类错误:递归方法printExpr 需要结果类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆