为什么 Scala 需要递归函数的返回类型? [英] Why does Scala require a return type for recursive functions?

查看:56
本文介绍了为什么 Scala 需要递归函数的返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面包含的代码片段中,我有一个递归函数调用,用于在网络调用失败时促进重试(Amazon SimpleDB 偶尔会返回 503 并要求重试.)

In the code snippet included below, I have a recursive function call, used to facilitate a retry if a network call fails (Amazon SimpleDB will occasionally return a 503 and require retry.)

当我尝试编译时,Scala 抱怨递归方法 simpledb_update 需要结果类型.

When I try to compile, the Scala complains recursive method simpledb_update needs result type.

// sends data to SimpleDB. Retries if necessary
def simpledb_update(name: String, metadata: Map[String,String], attempt: Int) = {
 try {
  db(config("simpledb_db")) += (name, metadata)
 } catch {
  case e =>
   // if it fails, try again up to 5 times
  if(attempt < 6)
  {
   Thread.sleep(500)
   simpledb_update(name, metadata, attempt + 1)
   } else
     AUlog(name + ": SimpleDB Failed")
   }
 }

为什么递归函数需要这样做?我的想法是只返回一个真/假布尔值以满足编译器......以下编译正常.

Why is this required on recursive functions? My thought is to just return a true/false boolean to satisfy the compiler... the following compiles fine.

// sends data to SimpleDB. Retries if necessary
 def simpledb_update(name: String, metadata: Map[String,String], attempt: Int): Boolean = {
 try {
  db(config("simpledb_db")) += (name, metadata)
  true
 } catch {
  case e =>
   // if it fails, try again up to 5 times
   if(attempt < 6)
   {
    Thread.sleep(500)
    simpledb_update(name, metadata, attempt + 1)
   } else
    AUlog(name + ": SimpleDB Failed")
    false
  }
}

推荐答案

据我所知,递归函数需要返回类型,因为类型推断算法的功能不足以确定所有递归函数的返回类型.

As I understand it, recursive functions need a return type because the type inference algorithm is not powerful enough to determine return types for all recursive functions.

然而,你不需要组成一个返回类型,你只需要声明你已经在使用的返回类型:Unit.Unit 是一种特殊类型,只有一个元素 ().它也是 Scala 中大多数语句"的类型,并且是为不需要返回任何内容但仅针对其副作用(如您的)执行的方法声明的返回类型.您可以像其他类型一样将您的方法声明为返回单元

However, you don't need to make up a return type, you just need to declare the return type you were already using: Unit. Unit is a special type with only one element (). It's also the type of most "statements" in Scala, and is the return type to declare for methods that don't need to return anything, but are executed only for their side-effects (as yours is). You can either declare your method as returning unit as you would other types

def simpledb_update(name: String, metadata: Map[String,String], attempt: Int):Unit = {

更惯用地,Scala 为返回单元的方法提供了一种特殊的语法,只需去掉返回类型和等号

def simpledb_update(name: String, metadata: Map[String,String], attempt: Int){

根据 Scala 风格指南,你应该更喜欢使用等号

According to scala style guide you should prefer to use equal sign

http://docs.scala-lang.org/style/declarations.html

这篇关于为什么 Scala 需要递归函数的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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