Help me understand this Scala code: scalaz IO Monad

家住魔仙堡 提交于 2019-12-05 16:23:48
agilesteel

Yes you are right, well almost; io.IO.apply gets called with a so called "by name" parameter which is basically a function which takes nothing (Unit) and returns A. The cool thing about is that when you pass an instance of A directly like new BufferedReader(new FileReader(f)), it will be converted to something like () => new BufferedReader(new FileReader(f)).

As a result of apply you get an instance of an IO[BufferedReader] which defines a method def unsafePerformIO which simply returns the instance of the captured BufferedReader.

Daniel C. Sobral

Complementing agilesteel's answer, the code

def bufferFile(f: File) = IO {   new BufferedReader(new FileReader(f)) }

Is equivalent to

def bufferFile(f: File) = new IO[A] {
  def unsafePerformIO = { new BufferedReader(new FileReader(f)) }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!