gpt4 book ai didi

scala - 在 Scala 中显式提供方法返回类型或变量类型的好处

转载 作者:行者123 更新时间:2023-12-01 07:25:50 24 4
gpt4 key购买 nike

这个问题可能很愚蠢,但我有点困惑,这是在 Scala 中最好的方法。
在 Scala 中,编译器进行类型推断并为每个变量或方法分配最接近的(或可能是限制性的)类型。
我是 Scala 的新手,从许多示例代码/库中,我注意到在很多地方人们大部分时间都没有明确提供类型。但是,在我编写的大部分代码中,我曾经/仍然明确提供类型。例如:

val someVal: String = "def"

def getMeResult() : List[String]= {
val list:List[String] = List("abc","def")
list
}

我开始专门为方法返回类型写这个的原因是,当我写一个方法本身时,我知道它应该返回什么。因此,如果我明确提供返回类型,我就可以查明我是否犯了任何错误。此外,我觉得通过阅读返回类型本身更容易理解该方法返回的内容。否则,我将不得不检查最后一条语句的返回类型。

所以我的问题/怀疑是:
1. 编译器不需要做太多推断,所以编译时间会更短吗?还是关系不大?
2. scala 世界的正常标准是什么?

最佳答案

来自“Scala in Depth”第4.5章 :

For a human reading a nontrivial method implementation, infering thereturn type can be troubling. It’s best to explicitly document andenforce return types in public APIs.


来自“Programming in Scala”第2章 :

Sometimes the Scala compiler will require you to specify the resulttype of a function. If the function is recursive, for example, youmust explicitly specify the function’s result type.

It is often a good idea to indicate function result types explicitly.Such type annotations can make the code easier to read, because thereader need not study the function body to figure out the inferredresult type.


来自“Scala in Action”第2.2.3章 :

It’s a good practice to specify the return type for the users of thelibrary. If you think it’s not clear from the function what its returntype is, either try to improve the name or specify the return type.


来自《Programming Scala》第一章 :

Recursive functions are one exception where the execution scopeextends beyond the scope of the body, so the return type must bedeclared.

For simple functions perhaps it’s not that important to show itexplicitly. However, sometimes the inferred type won’t be what’sexpected. Explicit return types provide useful documentation for thereader. I recommend adding return types, especially in public APIs.

You have to provide explicit return types in the following cases:

  • When you explicitly call return in a method.
  • When a method is recursive.
  • When two or more methods are overloaded and one of them calls another; the calling method needs a return type annotation.
  • When the inferred return type would be more general than you intended, e.g., Any.

关于scala - 在 Scala 中显式提供方法返回类型或变量类型的好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28513415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com