问题描述
Scala 赋值而不是赋值给 Unit 的动机是什么?
What is the motivation for Scala assignment evaluating to Unit rather than the value assigned?
I/O 编程中的一个常见模式是做这样的事情:
A common pattern in I/O programming is to do things like this:
while ((bytesRead = in.read(buffer)) != -1) { ...
但这在 Scala 中是不可能的,因为...
But this is not possible in Scala because...
bytesRead = in.read(buffer)
.. 返回 Unit,而不是 bytesRead 的新值.
.. returns Unit, not the new value of bytesRead.
将函数式语言排除在外似乎是一件有趣的事情.我想知道为什么要这样做?
Seems like an interesting thing to leave out of a functional language.I am wondering why it was done so?
推荐答案
我主张让赋值返回赋值而不是单位.Martin 和我在这个问题上反复讨论,但他的论点是,将一个值放在堆栈上只是为了在 95% 的时间内将其弹出是浪费字节码,并且会对性能产生负面影响.
I advocated for having assignments return the value assigned rather than unit. Martin and I went back and forth on it, but his argument was that putting a value on the stack just to pop it off 95% of the time was a waste of byte-codes and have a negative impact on performance.
这篇关于Scala 赋值计算 Unit 而不是赋值的动机是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!