以下是我们在scala中定义函数的方式
def printName() : Any = { println ("vikrant") }
def printName() : Unit = { println ("vikrant") }
“=”只是一种语法还是有目的?之所以问这个是因为当我没有提到返回类型时我可以跳过这个,如下所示
def printName() { println ("vikrant") }
最佳答案
如果方法返回 Unit
,您可以省略 =
(称为 过程语法),但这是非常不鼓励的(它有已被弃用,甚至有人讨论过 remove it )。来自 the style guide in the docs :
Methods should be declared according to the following pattern:
def foo(bar: Baz): Bin = expr
Procedure Syntax: Avoid the procedure syntax, as it tends to be confusing for very little gain in brevity.
// don't do this
def printBar(bar: Baz) {
println(bar)
}
// write this instead
def printBar(bar: Bar): Unit = {
println(bar)
}
生成的字节码没有区别。这只是语法糖。参见 the Scala specification 的第 4.6.3 节,它说:
Special syntax exists for procedures, i.e. functions that return the
Unit
value()
. A procedure declaration is a function declaration where the result type is omitted. The result type is then implicitly completed to theUnit
type.
因此它被编译为相同的代码。如果您使用 -Xfuture
选项,此功能会发出警告:
warning: Procedure syntax is deprecated. Convert procedure
foo
to method by adding: Unit =
.
在 Scala 中,每个方法都会返回一个值(不同于其他语言,这些语言的方法是 void
并且不返回任何内容)。在其他语言中为 void
的方法通常在 Scala 中返回 Unit
(例如您的 printName
示例)。
您可以将任何方法声明为返回 Unit
,而不管 =
之后的表达式的值。这是一种称为值丢弃 的语言功能,更多解释 here .
关于function - 在 Scala 中,为什么我们在定义方法时需要 "="?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29972884/