function - 在 Scala 中,为什么我们在定义方法时需要 "="?

标签 function scala functional-programming

以下是我们在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 the Unit 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/

相关文章:

Mysql最小函数

c++ - 通常对函数名的非限定查找与对变量名的查找不同吗?

Scala future 基础知识

scala - Slick group by 与其他领域

string - 如何在Elixir中循环遍历字符串中的每个字符?

javascript - 是否可以重写JavaScript的apply函数?

sql-server - 如何在 Sql Server 函数内执行字符串的技巧

javascript - 如何在类中运行函数。 JavaScript

scala - 一阶逻辑的通用量词和存在量词

scala - fp 风格的做法是什么 "naive hashmap"