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

前端 未结 3 457
轮回少年
轮回少年 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:09

    What Rex Kerr suggests in his comment is the following:

    val md = MessageDigest.getInstance("MD5")
    val input = new FileInputStream("foo.txt")
    val buffer = new Array[ Byte ]( 1024 )
    Stream.continually(input.read(buffer))
      .takeWhile(_ != -1)
      .foreach(md.update(buffer, 0, _))
    md.digest
    

    The key is the Stream.continually. It gets an expression which is evaluated continually, creating an infinite Stream of the evaluated expression. The takeWhile is the translation from the while-condition. The foreach is the body of the while-loop.

提交回复
热议问题