Come esercizio, ho provato a creare una conversione implicita che accetterebbe una funzione e produrrebbe a Runnable
. In questo modo potresti chiamare metodi Java che accettano Runnable
oggetti e li usano come chiusure.
La conversione implicita è abbastanza semplice:
implicit def funToRunnable(fun : Unit) = new Runnable() { def run = fun }
Tuttavia non so come chiamarlo. Come passi in una funzione no-arg che restituisce l'Unità, senza averla subito valutata? Ad esempio, mi piacerebbe quanto segue per stampare "12", ma invece stampa "21" perché print("2")
viene valutato in una volta.
var savedFun : Runnable = null
def save(r : Runnable) = { savedFun = r }
save(print("2"))
print("1")
savedFun.run()
Come faccio a dire al compilatore di trattare print("2")
come il corpo di una funzione, non qualcosa da valutare contemporaneamente? Alcune possibilità che ho provato, come ad esempio
save(() => print("2"))
o
save(=> print("2"))
non sono una sintassi legale
risposte:
23 per risposta № 1arg, ho appena risposto alla mia domanda. Ho implementato la conversione implicita in modo errato. L'implementazione corretta è
implicit def funToRunnable(fun: () => Unit) = new Runnable() { def run() = fun() }
e tu lo chiami così:
save(() => print("2"))
Questo produce "12"
12 per risposta № 2
Se volevi vivere pericolosamente, potresti convertire qualsiasi cosa in un eseguibile:
implicit def whateverToRunnable[F](f: => F) = new Runnable() { def run() { f } }
scala> val t = new Thread(println("Hello"))
t: java.lang.Thread = Thread[Thread-2,5,main]
scala> t.start()
Hello
O potresti creare il tuo thread-creator-and-starter:
def thread[F](f: => F) = (new Thread( new Runnable() { def run() { f } } )).start
scala> thread { println("Hi"); Thread.sleep(1000); println("Still here!") }
Hi
scala> Still here!
Se si desidera restituire il thread, quindi
def thread[F](f: => F) = {
val t = new Thread( new Runnable() { def run() { f } } )
t.start()
t
}
Ma tutto ciò, anche se utile, è forse anche meno utile di scala.actors.Futures
(testato solo su 2.8):
scala> import scala.actors.Futures
scala> val x = Futures.future { Thread.sleep(10000); "Done!" }
x: scala.actors.Future[java.lang.String] = <function0>
scala> x.isSet
res0: Boolean = false
scala> x.isSet
res1: Boolean = false
scala> x() // Waits until the result is ready....
res2: java.lang.String = Done!
5 per risposta № 3
Interessante, in questo modo è possibile eseguire codice che riceve un Runnable
e passare una chiusura.
Vedere:
scala> new Thread( () => print( "Hello" ) ).start()
<console>:5: error: overloaded method constructor Thread with alternatives (java.lang.ThreadGroup,java.lang.Runnable,java.lang.String,Long)java.lang.Thread <and> (java.lang.ThreadGroup,java.lang.Runnable,java.lang.String)java.lang.Thread <and> (java.lang.Runnable,java.lang.String)java.lang.Thread <and> (java.lang.ThreadGroup,java.lang.String)java.lang.Thread <and> (java.lang.String)ja...
new Thread( () => print( "Hello" ) ).start()
scala> implicit def funcToRunnable( func : () => Unit ) = new Runnable(){ def run() = func() }
funcToRunnable: (() => Unit)java.lang.Object with java.lang.Runnable
scala> def doRun( runnable: Runnable ) = runnable.run
doRun: (Runnable)Unit
scala> doRun( () => print("Hola"))
Hola
scala> new Thread(()=>print("Hello")).start()
scala> Hello
4 per risposta № 4
In realtà, puoi farlo ancora meglio con l'argomento call-by-name:
implicit def runnable(f: => Unit): Runnable = new Runnable() { def run() = f }
Uso:
import concurrent.ExecutionContext.Implicits.global._
execute(print("hello"))
0 per risposta № 5
Un altro modo per eseguire codice in un thread diverso:
scala.actors.Actor.actor { ...doSomething()... }