Created
July 11, 2016 13:38
-
-
Save takeouchida/013d6918777cbaf951f51aae45a9a989 to your computer and use it in GitHub Desktop.
This file contains 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 SpecExample extends App { | |
// Application code | |
case class ResourceX(name: String) | |
case class ResourceY(name: String) | |
def createResourceX(name: String): ResourceX = { println(s"Creating $name"); ResourceX(name) } | |
def createResourceY(name: String): ResourceY = { println(s"Creating $name"); ResourceY(name) } | |
// Utility code for testing | |
trait Closeable[R] { | |
def close(res: R) | |
} | |
implicit object ResourceXCloseable extends Closeable[ResourceX] { | |
override def close(res: ResourceX): Unit = println(s"Close $res") | |
} | |
implicit object ResourceYCloseable extends Closeable[ResourceY] { | |
override def close(res: ResourceY): Unit = println(s"Close $res") | |
} | |
class ResourceWrapper[R](res: R)(implicit ev: Closeable[R]) { | |
def foreach[T](block: R => T) = | |
try { | |
block(res) | |
} finally { | |
ev.close(res) | |
} | |
} | |
implicit def wrapResource[R](res: R)(implicit ev: Closeable[R]) = new ResourceWrapper(res) | |
// Test case | |
for ( | |
x <- createResourceX("foo"); | |
y <- createResourceY("bar") | |
) { | |
println(s"Some test cases: $x, $y") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment