What is the Scala equivalent of F#'s async workflows?
For example, how would following F# snippet translate to idiomatic Scala?
open System.Net
open Microsoft.FSharp.Control.WebExtensions
let urlList = [ "Microsoft.com", "http://www.microsoft.com/"
"MSDN", "http://msdn.microsoft.com/"
"Bing", "http://www.bing.com"
]
let fetchAsync(name, url:string) =
async {
try
let uri = new System.Uri(url)
let webClient = new WebClient()
let! html = webClient.AsyncDownloadString(uri)
printfn "Read %d characters for %s" html.Length name
with
| ex -> printfn "%s" (ex.Message);
}
let runAll() =
urlList
|> Seq.map fetchAsync
|> Async.Parallel
|> Async.RunSynchronously
|> ignore
runAll()
The F[_] simply means that F is a type parameter , which is itself a type constructor or a type with a type parameter . As we stated earlier, such a type can be a List , Option , or even a Scala Future .
The f Interpolator Prepending f to any string literal allows the creation of simple formatted strings, similar to printf in other languages. When using the f interpolator, all variable references should be followed by a printf -style format string, like %d . Let's look at an example: Scala 2 and 3.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
Scala string is an immutable object that means the object cannot be modified. Each element of a string is associated with an index number. The first character is associated with the number 0, the second with the number 1, etc. Class java. lang.
You code more or less directly can be translated to Scala using Futures
(with some important features lost, though):
import scala.actors.Futures
import Futures._
val urlList = Map("Microsoft.com" -> "http://www.microsoft.com/",
"MSDN" -> "http://msdn.microsoft.com/",
"Bing" -> "http://www.bing.com")
def fetchAsync(name: String, url: String) = future {
// lengthy operation simulation
Thread.sleep(1000)
println("Fetching from %s: %s" format(name, url))
}
def runAll =
//Futures.awaitAll( <- if you want to synchronously wait for the futures to complete
urlList.map{case (name, url) => fetchAsync(name, url)}
//)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With