Reputation: 585
My title is probably not describing the problem piece of code I am trying to understand:
Here is the piece of code:
def getMeConcurrentInputStream[A, I <: InputStream](in:I)(fn:I => A):Future[A] = {
future {
fn(in)
}andThen {
case all => in.close()
}
}
I am trying to understand what to make of this function. What is this:
[A, I <: InputStream](in:I)(fn:I => A)
and what is this: (in:I)(fn:I => A)
and the function is returning a Future? How would I interpret: Future[A]
How do I interpret all of the above? And how would I use this function by invoking it from someplace else in the code?
Upvotes: 1
Views: 267
Reputation: 83245
def getMeConcurrentInputStream
function named getMeConcurrentInputStream
[A, I <: InputStream]
that with generic type A
and a type I
which is InputStream
or a subclass of it.
(in:I)(fn:I => A)
with a parameter list of an I
and a parameter list of a function accepting I
and returning A
:Future[A] = {
returning a Future
of type A
future {
which creates a Future
in the in-scope implicit ExecutionContext
fn(in)
and the future calls the function fn
with argument in
.
}andThen {
and afterwords, whether successful or a failure,
case all =>
in all cases
in.close()
call .close()
on in
.
This function wraps some operation involving an InputStream
in a Future
and closes it when it is done.
For example, suppose I wanted to asynchronously read the first byte of a file, and then print it out. I could do this:
val fileInputStream = new FileInputStream("example.txt")
val myFuture = getMeConcurrentInputStream(fileInputStream) { inputStream =>
inputStream.read()
}
myFuture.map(println)
Personally, I can't see much use for this function, but there you go.
Upvotes: 5