You can specify a type bound that require a type to support certain methods:
object Example2 {
def using[T <: {def close(): Unit}, S](obj: T)
(operation: T => S) = {
val result = operation(obj)
obj.close()
result
}
val str = using(new BufferedReader(new InputStreamReader(new FileInputStream("/tmp/readme")))) {
obj => {
val res = obj.readLine()
res match {
case null => None
case x => Some(x)
}
}
}
}
0 comments:
Post a Comment