简体   繁体   中英

Scala: a method with a parameteric or generic type argument that returns a Future

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM