Loaner Pattern in Scala

后端 未结 2 510
滥情空心
滥情空心 2020-12-01 02:23

Scala in Depth demonstrates the Loaner Pattern:

def readFile[T](f: File)(handler: FileInputStream => T): T = {
  val resource = new java.io.FileI         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 03:07

    With the Loan pattern it is important to know when the "bit" of code that is going to actually call your loaned resource is going to use it.

    If you want to return a future from a loan pattern I advise to not create it inside the function that is passed to the loan pattern function.

    Don't write

    readFile("text.file")(future { doSomething })
    

    but do:

    future { readFile("text.file")( doSomething ) }
    

    what I usually do is that I define two types of loan pattern functions: Synchronous and Async

    So in your case I would have:

    def asyncReadFile[T](f: File)(handler: FileInputStream => T): Future[T] = {
      future{
        readFile(f)(handler)
      }
    }
    

    This way you avoid calling closed resources. And you reuse your already tested and hopefully correct code of the Synchronous function.

提交回复
热议问题