What is the proper way to code a read-while loop in Scala?

前端 未结 3 455
轮回少年
轮回少年 2021-01-31 09:40

What is the \"proper\" of writing the standard read-while loop in Scala? By proper I mean written in a Scala-like way as opposed to a Java-like way.

Here is the code I

3条回答
  •  生来不讨喜
    2021-01-31 10:18

    What about a curried function? You 11 lines of Scala code become:

    val md = MessageDigest.getInstance(hashInfo.algorithm)
    val input = new FileInputStream("file")
    iterateStream(input){ (data, length) => 
        md.update(data, 0, length)
    }
    md.digest
    

    The iterateStream function on line 3, which you could add to a library is:

    def iterateStream(input: InputStream)(f: (Array[Byte], Int) => Unit){
        val buffer = new Array[Byte](512)
        var curr = input.read(buffer)
        while(curr != -1){
            f(buffer, curr)
            curr = input.read(buffer)
        }
    }
    

    The ugly duplicated code (where the input is read) ends up in the library, well tested and hidden away from the programmer. I feel that the first block of code is less complex than the Iterator.continually solution.

提交回复
热议问题