简体   繁体   English

在Scala REPL中使用val和def定义函数之间的区别?

[英]The differences between using `val` and `def` for function definition in Scala REPL?

I defined two functions(method) in Scala REPL: 我在Scala REPL中定义了两个函数(方法):

scala> val b=(x:Int)=>x+1
b: Int => Int = <function1>

scala> def c(x:Int)=x+1
c: (x: Int)Int

And the usage: 以及用法:

scala> b(1)
res4: Int = 2

scala> c(1)
res5: Int = 2

While both definition works, it seems that b and c have different type. 虽然两个定义都起作用,但bc似乎具有不同的类型。 And I was wondering whether there are some differences between them. 我想知道它们之间是否存在一些差异。 Why doesn't Scala use the same type for b and c ? 为什么Scala不对bc使用相同的类型? Does anyone have ideas about this? 有人对此有想法吗?


Not duplicate: 不重复:

This question is not a duplicate of the linked question. 该问题不是链接问题的重复项。 Even though it asks about the difference between using def and val to define a function, the code example makes it clear that the asker is confused about the difference between methods and functions in Scala. 即使它询问使用def和val定义函数之间的区别,该代码示例也清楚地表明,问问者对Scala中方法和函数之间的区别感到困惑。 The example doesn't use a def to define a function at all. 该示例根本不使用def定义函数。 – Aaron Novstrup 7 hours ago – Aaron Novstrup 7小时前

The use of def creates a method (in the case of the REPL it will create a method in some global invisible object), val instead will create an anonymous function and assign it to the symbol you specified. 使用def会创建一个方法(在REPL的情况下,它将在某些全局不可见对象中创建一个方法),而val会创建一个匿名函数并将其分配给您指定的符号。

When invoking those they are pretty much the same thing; 当调用它们时,它们几乎是同一件事。 when you pass them around there is a difference but Scala hides it from you by performing the ETA expansion transparently. 当您将它们传递给您时,会有所不同,但是Scala通过透明地执行ETA扩展将其隐藏起来。 As an example if you define this: 例如,如果您定义以下内容:

def isEven(i: Int): Boolean = i % 2 == 0

And then call 然后打电话

list.filter(isEven)

Scala is transforming that for you in a way that is similar to using the val way instead; Scala正在以一种类似于使用val方法的方式为您转换它。 take it as a pseudo-code as I don't know so well the scala internals but at at high level this is what happens: 把它当作伪代码,因为我对scala内部并不十分了解,但总的来说会发生以下情况:

list.filter((i: Int) => isEven(i))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM