- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这个问题可能很愚蠢,但我有点困惑,这是在 Scala 中最好的方法。
在 Scala 中,编译器进行类型推断并为每个变量或方法分配最接近的(或可能是限制性的)类型。
我是 Scala 的新手,从许多示例代码/库中,我注意到在很多地方人们大部分时间都没有明确提供类型。但是,在我编写的大部分代码中,我曾经/仍然明确提供类型。例如:
val someVal: String = "def"
def getMeResult() : List[String]= {
val list:List[String] = List("abc","def")
list
}
最佳答案
来自“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.
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.
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.
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/
我是一名优秀的程序员,十分优秀!