zoukankan      html  css  js  c++  java
  • kotlin实现流读取

    在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 {
    var read: Int = -1
    `in`.use { input ->
    output.use {
    while ({ read = input.read();read }() != -1) {
    it.write(read)
    }
    }
    }
    } catch (t: Throwable) {
    t.printStackTrace()
    }
    }

    第二种写法,二逼青年:

    通过正常写法来实现

    fun someFunc(`in`: InputStream, output: OutputStream) {
    try {
    var read: Int = `in`.read()
    `in`.use { input ->
    output.use {
    while (read != -1) {
    it.write(read)
    read = input.read()
    }
    }
    }
    } catch (t: Throwable) {
    t.printStackTrace()
    }
    }

    第三种写法,优秀青年:

    通过使用also扩展函数来实现

    fun someFunc(`in`: InputStream, output: OutputStream) {
    try {
    var read: Int = -1
    `in`.use { input ->
    output.use {
    while (input.read().also { read = it } != -1) {
    it.write(read)
    }
    }
    }
    } catch (t: Throwable) {
    t.printStackTrace()
    }
    }

    我们来看一下also函数是什么样的:

    also函数,传入一个拉姆达并且调用,拉姆达的参数是调用also的实例,然后返回实例,很好理解,就是哪个调用的就返回哪个,并且将它传入拉姆达里面。

    举个栗子:


    data class User(val name: String, val age: Int)

    fun getMain() {
    val userOut = User("jowan", 25)
    println(userOut.also {
    println("also---$it") // 这里的it表示什么,同时打印什么
    }) // 这里会打印什么
    }
    9
    打印什么应该猜到了吧!!

  • 相关阅读:
    Balanced Binary Tree
    Convert Sorted List to Binary Search Tree
    Convert Sorted Array to Binary Search Tree
    Binary Tree Zigzag Level Order Traversal
    Validate Binary Search Tree
    Binary Tree Level Order Traversal II
    Binary Tree Level Order Traversal
    Maximum Depth of Binary Tree
    如何把U盘的两个盘或者多个盘合成一个
    bugku 想蹭网先解开密码
  • 原文地址:https://www.cnblogs.com/vana/p/10903341.html
Copyright © 2011-2022 走看看