Created
September 29, 2015 20:43
-
-
Save sam/7f3780e5267e0de7be7c to your computer and use it in GitHub Desktop.
Is there a way to zip nested functions A => T and B => T into a (A, B) => T?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object helpers { | |
type Closeable = { def close() } | |
def using[T, S <: Closeable](source: S)(f: S => T) = { | |
val result = f(source) // Simplified for the example. | |
source.close() | |
result | |
} | |
} | |
// We can use this like: | |
import java.io.File | |
val out = new File("test") | |
using(new PrintWriter(out)) { _ println "Bob" } | |
// or: | |
using(Source.fromFile(out)) { _ println "Bob" } | |
// What if you want to nest the statements though? | |
using(new PrintWriter(out)) { out => | |
using(new WebClient) { client => | |
out print client.getPage(new URL("http://google.com")).asInstanceOf[HtmlPage].asXml() | |
} | |
} | |
// Ideally I could write the above something like this instead: | |
(using(new PrintWriter(out)) zip using(new WebClient)) { (out, client) => | |
out print client.getPage(new URL("http://google.com")).asInstanceOf[HtmlPage].asXml() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is one way to do it.