Scala 编译器通常可以推断方法的返回类型,但在某些情况下需要指定返回类型。例如,递归方法需要指定返回类型。
我注意到有时会收到错误消息“重载方法(方法名)需要返回类型”,但这并不是一般规则,必须始终为重载方法指定返回类型(我有没有收到此错误的示例)。
到底什么时候需要为一般方法和特别是重载方法指定返回类型?
The Scala compiler can often infer return types for methods, but there are some circumstances where it's required to specify the return type. Recursive methods, for example, require a return type to be specified.
I notice that sometimes I get the error message "overloaded method (methodname) requires return type", but it's not a general rule that return types must always be specified for overloaded methods (I have examples where I don't get this error).
When exactly is it required to specify a return type, for methods in general and specifically for overloaded methods?
发布评论
评论(1)
第 2 章:少输入,多做 href="http://programming-scala.labs.oreilly.com/index.html" rel="nofollow noreferrer">Programming Scala 书中提到:
例子:
基本上,指定返回类型可能是一个很好的做法,即使 Scala 可以推断它。
兰德尔·舒尔茨评论:
并且由于您可能希望在返回类型中公开最小接口(例如,请参见此 SO问题),这种推断可能会妨碍。
关于最后一个场景(“当推断的返回类型比您预期的更通用时”),Ken Bloom补充道:
(触发“比预期返回类型更一般的返回类型是:”的错误代码是:
,我错误地解释了它List[Any] 因为返回一个空列表,但 Ken 指出:
The Chapter 2. Type Less, Do More of the Programming Scala book mentions:
Example:
Basically, specifying the return type can be a good practice even though Scala can infer it.
Randall Schulz comments:
And since you may want to expose the minimal interface in your return type (see for instance this SO question), this kind of inference might get in the way.
And about the last scenario ("When the inferred return type would be more general than you intended"), Ken Bloom adds:
(The faulty code which triggers a "more general than expected return type was:
, which I incorrectly interpreted and List[Any] because returning an empty List, but Ken called it out: