Get the App
SLTechnology News&Howtos  ›  Servers  › 

What expressions does Scala have?

Shulou Source: shulou.com Published: 2022-05-31 21:24:45 11月04日 Update

This article introduces the relevant knowledge of "what expressions does Scala have". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. conditional expression

If else can return a value, if (x > 0) 1 else-1, and the return value of this expression is of type Int,-1 or 1. So you can write val I = if (x > 0) 1 else-1. In fact, I prefer to write if (x > 0), I prefer to use val, the former is more functional and val is used, and the latter is more instructive and must be var.

2. Unit,if (x > 0) 1 if the return value is 1 if x > 0, this is no problem, but what about x < 0? This expression does not return a value, it doesn't matter, there is a Scala.Unit in Scala, write (), which is equivalent to void.

Third, with regard to semicolons, scala can write but not write, but there is a situation that must be written, one line to write multiple statements, in fact, do not know this matter, why do you have to write multiple statements in one line.

IV. Block expression

There is something similar in java, but the difference is that scala also has a return value, the return value is x + y, and the last sentence is x + y, which is incomprehensible in java, but in scala, this is equivalent to the return value of this block expression.

Val res = {val x = 10; val y = 20; x + y}

Fifth, there is no obvious difference between While,scala and java. As far as I understand it, while is a more prescriptive thing and should be avoided as far as possible in scala.

6. For, for (I

Tags: Expressions things functions statements procedures almost parameters multiple one line content writing actually that is cases instructions more knowledge loops differences favor Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Shulou Technology Shulou Information Docker Apple