我試圖找出在Scala中聲明函數時def
和var/val
之間的區別。在Scala中聲明一個使用def或var的函數
說我們有一個功能:
scala> def f(x: Int) = { x * 2 }
f: (x: Int)Int
而另一個函數g:
scala> var g = (x:Int) => x*2
g: Int => Int = <function1>
顯然,他們是通過以下方式相同:
scala> f(2)
res0: Int = 4
scala> g(2)
res1: Int = 4
不過,我可以做
g = f
g: Int => Int = <function1>
但不
scala> f = g
<console>:13: error: missing arguments for method f;
follow this method with `_' if you want to treat it as a partially applied function
val $ires6 = f
^
<console>:10: error: reassignment to val
f = g
^
問題1:爲什麼會發生這種情況? 我猜def
映射到val
。
問題2:如果我在聲明克使用VAL而不是VAR,他們是等價?如果不是,那麼有什麼區別?
我再試試:
scala> def three(timetwo:(Int) => Int) = { timetwo(3) }
three: (timetwo: Int => Int)Int
scala> three(g)
res47: Int = 6
scala> three(f)
res48: Int = 6
問題3:意思(x: Int)Int
是一樣的Int => Int = <function1>
?如果是這樣,有什麼情況我們應該相互贊成?
事情是越來越有線與_
(下劃線),
scala> three(f _)
res49: Int = 6
scala> three(g _)
<console>:11: error: type mismatch;
found :() => Int => Int
required: Int => Int
three(g _)
^
問題4:爲什麼會發生這種情況? Scala中_
(下劃線)的用法是什麼?
[Scala中定義函數的兩種方式可能的重複。有什麼區別?](http://stackoverflow.com/questions/5009411/two-ways-of-defining-functions-in-scala-what-is-the-difference) –
http://stackoverflow.com/問題/ 2529184 /差之間-方法和 - 功能合階 – Maxim