This is the first article in my series that provides an overview of the changes in Scala 3.
Let's start with the most controversial innovations: optional curly braces and
new syntax for control constructs.
The optional curly braces make Scala code more like Python or Haskell, which uses indentation to group expressions. Let's take a look at examples taken from the 3rd edition of my book Programming Scala , which is now in preparation for publication.
Optional curly braces
First, let's look at declaring a type using the old and new syntax. This also works for packages if we declare multiple packages in the same file.
//
trait Monoid2[A] {
def add(a1: A, a2: A): A
def zero: A
}
//
trait Monoid3[A]:
def add(a1: A, a2: A): A
def zero: A
The new syntax closely resembles Python, and it can be confusing if you constantly switch between the two languages.
You can mix old and new style, the Dotty compiler (soon to be renamed to Scala 3) will compile such code without errors.
. , =
, :
.
def m2(s: String): String = {
val result = s.toUpperCase
println(s"output: $result")
result
}
def m3(s: String): String =
val result = s.toUpperCase
println(s"output: $result")
result
:
Scala. , =
, . , .
partial functions, match expressions try-catch-finally ( ):
val o2:Option[Int] => Int = {
case Some(i) => i
case None => 0
}
val o3:Option[Int] => Int =
case Some(i) => i
case None => 0
0 match {
case 0 => "zero"
case _ => "other value"
}
0 match
case 0 => "zero"
case _ => "other value"
Scala Java. ? , , Python, Scala. , Python , , , Scala. data science, Python, data engineering, Scala. Scala Python .
, . , , , Scala . :
import scala.annotation.tailrec
@tailrec def loop(whileTrue: => Boolean)(f: => Unit): Unit =
f
if (whileTrue) loop(whileTrue)(f)
var i=5
loop(i > 0) {
println(i)
i -= 1
}
var j=5
loop(j > 0): // ERROR
println(j)
j -= 1
: "" . loop
while
. . (, .)
Programming Scala, , . , - Scala 3, . , . Scala- . , : Scala Python ( Haskell) — .
, if
, for
while
. :
for (i <- 0 until 5) println(i) //
for i <- 0 until 5 do println(i) //
for i <- 0 until 5 yield 2*i
for i <- 0 until 10
if i%2 == 0
ii = 2*i
yield ii
val i = 10
if (i < 10) println("yes") //
else println("no")
if i < 10 then println("yes") //
else println("no")
for
while
, do
. for
yield
. if
then
.
. -new-syntax
, -old-syntax
— .
-rewrite
, , , .
. , .
Scala 2, . , , . . Java- - , .
, - . .