Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the motivation for Scala assignment evaluating to Unit rather than the value assigned?

What is the motivation for Scala assignment evaluating to Unit rather than the value assigned?

A common pattern in I/O programming is to do things like this:

while ((bytesRead = in.read(buffer)) != -1) { ... 

But this is not possible in Scala because...

bytesRead = in.read(buffer) 

.. 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?

like image 634
Graham Lea Avatar asked Jan 04 '10 10:01

Graham Lea


People also ask

What is the purpose of an assignment statement?

An assignment statement sets the current value of a variable, field, parameter, or element. The statement consists of an assignment target followed by the assignment operator and an expression. When the statement is executed, the expression is evaluated and the resulting value is stored in the target.

What is an assignment statement explain with an example?

An assignment statement gives a value to a variable. For example, ... the variable may be a simple name, or an indexed location in an array, or a field (instance variable) of an object, or a static field of a class; and. the expression must result in a value that is compatible with the type of the variable .

Does assignment return a value?

Value of an assignmentIn some programming languages, an assignment statement returns a value, while in others it does not.

What does assign mean in programming?

An assignment is a statement in computer programming that is used to set a value to a variable name. The operator used to do assignment is denoted with an equal sign (=). This operand works by assigning the value on the right-hand side of the operand to the operand on the left-hand side.


1 Answers

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.

like image 184
David Pollak Avatar answered Oct 06 '22 01:10

David Pollak