且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 Scala 需要递归函数的返回类型?

更新时间:2022-02-12 23:59:41

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

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