在Scala中编写read-while循环的正确方法是什么? [英] What is the proper way to code a read-while loop in Scala?

查看:146
本文介绍了在Scala中编写read-while循环的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中编写标准read-while循环的正确是什么?正确地说,我的意思是用类似Scala的方式编写而不是类似Java的方式。

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.

以下是我在Java中的代码:

Here is the code I have in Java:

MessageDigest md = MessageDigest.getInstance( "MD5" );
InputStream input = new FileInputStream( "file" );
byte[] buffer = new byte[1024];
int readLen;
while( ( readLen = input.read( buffer ) ) != -1 )
    md.update( buffer, 0, readLen );
return md.digest();

以下是我在Scala中的代码:

Here is the code I have in Scala:

val md = MessageDigest.getInstance( hashInfo.algorithm )
val input = new FileInputStream( "file" )
val buffer = new Array[ Byte ]( 1024 )
var readLen = 0
while( readLen != -1 )
{
    readLen = input.read( buffer )
    if( readLen != -1 )
        md.update( buffer, 0, readLen )
}
md.digest

Scala代码是正确的并且有效,但感觉非常非Scala-ish。首先,它是Java代码的字面翻译,充分利用了Scala的优势。而且它实际上比Java代码长!我真的觉得我错过了什么,但我无法弄清楚是什么。

The Scala code is correct and works, but feels very un-Scala-ish. For one it is a literal translation of the Java code, taking advantage of none of the advantages of Scala. Further it is actually longer than the Java code! I really feel like I'm missing something, but I can't figure out what.

我是Scala的新手,因此我提出的问题是避免陷入在Scala中编写Java风格代码的陷阱。我对Scala解决此类问题的方式比对Scala API可能提供的任何特定帮助方法更感兴趣来散列文件。

I'm fairly new to Scala, and so I'm asking the question to avoid falling into the pitfall of writing Java-style code in Scala. I'm more interested in the Scala way to solve this kind of problem than in any specific helper method that might be provided by the Scala API to hash a file.

(我在此问题中提前为我的临时Scala形容词道歉。)

(I apologize in advance for my ad hoc Scala adjectives throughout this question.)

推荐答案

根据他提到的Rex的帖子:

Based on Rex's post that he mentioned:

Stream.continually(input.read(buffer)).takeWhile(_ != -1).foreach(md.update(buffer, 0, _))

你应该用{...}行替换var readLen +它,它产生相同的结果。

You should replace the var readLen + while {...} lines with it, it produces the same result.

正如Rex所说,它适用于scala 2.8。

As Rex mentioned, it works with scala 2.8.

这篇关于在Scala中编写read-while循环的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆