scal中val和def之间的区别?

时间:2019-10-20 07:22:02

标签: scala functional-programming

我从斯卡拉(Scala)开始,在评估中有这种困惑。如果在val中,则在声明时会评估结果,然后为什么在调用该val名称时又会给我函数的主体。

scala> val pop = (x:Int,y:Int)=> println(s"$x $y is the number")
pop: (Int, Int) => Unit = <function2>

scala> pop(12,3)
12 3 is the number

scala> pop(12,3) //So is this expression evaluated again ? and if not how is it stored in the memory that if 12 and 3 will come as parameter then that value will be given back.
12 3 is the number
scala> pop
res6: (Int, Int) => Unit = <function2>
//why is it giving the body as it is already evaluated

可以声明没有参数的使用val的函数吗?

val som....which only prints say hello

1 个答案:

答案 0 :(得分:3)

在Scala中,函数是一流的值,因此pop value

(x:Int, y:Int) => println(s"$x $y is the number")

本身。这样的函数值可能看起来与说的值42完全不同,但仍然是常规值。例如,对比以下内容

val i: Int = 42                   // assigning value 42 to name i
val f: Int => String = i => "foo" // assigning value `i => "foo"` to name f

如果我们将pop的定义去糖化,

val pop: Function2[Int, Int, Unit] = new Function2[Int, Int, Unit] {
  def apply(x: Int, y: Int): Unit = println(s"$x $y is the number")
}

我们在其中看到pop的地方被分配了Function2类的实例,该实例包含一个apply方法。此外,pop(12, 3)可以降低

pop.apply(12,3)

我们看到的pop(12, 3)只是在Function2类上调用一个方法。对比pop

评估
pop
res6: (Int, Int) => Unit = <function2>
具有实例pop的函数 application

指向

pop(12,3)
12 3 is the number

pop val ue定义,因为我们无法更改其指向的功能,例如

pop = (i: Int) => i.toString // error: reassignment to val

没有参数的函数可以这样定义

val g = () => "I am function with no parameters"
g   // evaluates g
g() // applies function pointed to by g