在Java对流的读取是下面的那样,当前不要忘记流的关闭close
。
// java 代码
void someFunc(InputStream in, OutputStream out) throws IOException {
int read;
while ((read = in.read()) != -1) {
out.write(read);
}
}
但是在kotlin中等式不是一个表达式,所以不能那样子写,kotlin是这样的使用的,有几种写法:
在使用流或者数据库之类的资源需要关闭close
的情况下,可以使用use
扩展函数来实现自动关闭的操作
第一种写法,文艺青年:
通过闭包返回来实现
fun someFunc(`in`: InputStream, output: OutputStream) {
try {