1) E 'solo più comodo da usare, DSL soprattutto all'interno:
def printAndGet[T](f: => T) = {
val res = f
println(res + " printed")
res
}
scala> :paste
// Entering paste mode (ctrl-D to finish)
val k = printAndGet {
val a = 5
5 * a
}
// Exiting paste mode, now interpreting.
25 printed
k: Int = 25
2) => T
può essere solo un parametro di metodo o una funzione. E in realtà => T
e () => T
non sono intercambiabili:
scala> def aaa(f: => String) = f
aaa: (f: => String)String
scala> val a: Function1[() => String, String] = aaa _
<console>:8: error: type mismatch;
found : (=> String) => String
required: (() => String) => String
val a: Function1[() => String, String] = aaa _
^
Grazie a @ som-snytt, fоund questo:
scala> object O { def f(i: Int) = i; def f(i: => Int) = i + 1 }
defined object O
scala> O.f(5)
res12: Int = 5
scala> O.f(5: (=> Int))
<console>:1: error: no by-name parameter type allowed here
O.f(5: (=> Int))
^
Anche questa, che dovrebbe funzionare se si compila - ma non è così (Scala 2.11.2, 2.11.5 REPL si blocca solo):
scala> val k: (=> Int) => Int = O.f _
k: (=> Int) => Int = <function1>
scala> k(5) //should be 6
res18: Int = 5 //WTF?
Ultima sembra come un insetto
.210
3) Non esattamente, se si desidera che la stessa, solo convertire => T
in () => T
:
scala> def aaa(f: => String) = {f _}
aaa: (f: => String)() => String
Bytecode può anche essere diverso. Ad esempio, il compilatore sarà più probabile codice inline da => T
senza generare lambda per esso. Quindi, la differenza principale è che () => T
è in realtà un oggetto (cittadino di prima classe), => T
no.
4) vedere 1, ma a volte potrebbe essere necessario assicurarsi che l'utente sappia che il calcolo potrebbe essere ritardato - () => T
è meglio allora.
5) E 'parte di una firma tipo, basta guardare eta-espansione:
scala> def aaa(f: => String) = {f}
aaa: (f: => String)String
scala> aaa _ //convert method into a function
res7: (=> String) => String = <function1>
scala> val a: (=> String) => String = aaa _
a: (=> String) => String = <function1>
Tuttavia Scala non riconosce che tipo di indipendenza:
scala> val a: Function1[(=> String), String] = aaa _
<console>:1: error: no by-name parameter type allowed here
val a: Function1[(=> String), String] = aaa _
^
Considerate questo commento - https : //twitter.com/StewOConnor/status/633555338894020608 –