我是 Scala 新手,我知道它是一种非常丰富的语言。让我在语法方面陷入困境的一件事是函数创建。我知道大括号 {} 在许多上下文中被编译器解释为括号 () 的同义词,但以下内容我仍然不太明白。
以下是 Scala REPL 的输出:
scala> def index = List {}
index: List[Unit]
scala> def index = List ()
index: List[Nothing]
第一季度。
如果我正确理解上述内容,我将创建一个名为 index
的函数创建一个新的列表( new
被省略,因为隐式调用 apply
方法,对吧?)。
我看到Unit
(相当于 Java 中的 null
?)是使用大括号 {} 时列表的类型。但使用parens()时Nothing是类型。
第二季度。
有人可以用简单的术语解释一下(如果可能的话){}
的使用之间的区别和()
在创建函数中还有什么Nothing
代表什么?
编辑 - 那么以下内容是等效的吗?
def index = List {val a = 1; a}
def index = List ({val a = 1; a})
我也对术语 function
有点挣扎。和method
似乎可以互换使用。
以上两者都可以被视为function
,这样说是否正确?或method
?
还是取决于你与谁交谈?
最佳答案
If I understand the above correctly, I am creating a function called index that creates a new List (new is omitted because of implicit call to apply method right?).
(new is omitted because of implicit call to apply method right?)
是的,有点。 List.apply
构造List
并将其返回给您的方法。
def index = List {}
创建一个名为index的方法,该方法创建一个新的List
通过调用 List.apply
.
Can someone explain, in simple terms (if possible), the difference between the use of {} and () in creating functions and also what Nothing represents?
空花括号{}
表示一个匿名函数,而不是一个简单的元素列表。例如我可以这样做:
scala> def index = List {val a = 1; a}
index: List[Int]
您的方法相当于(省略括号):
def index = List({})
匿名函数的结果被传递给apply
。当大括号为空时,匿名函数的返回类型为 Unit
。所以我们得到List[Unit]
.
def index = List ()
始终返回空 List
。但是,由于您没有注释,编译器无法从中推断类型,因此将其推断为 Nothing
,它是所有其他类型的子类型。这使我们能够组合 List[Nothing]
与 List[Int]
并仍然可以编译。
I see that Unit (equivalent to null in Java?) ...
Unit
是不返回任何内容的方法的返回类型。类似于 void
在 Java 中,而不是 null
.
关于SCALA 创建函数语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29281300/