Scala
Values cannot be re-assigned
The type of a value can be omitted and inferred, or it can be explicitly stated:
val x: Int = 1 + 1
Variables are like values, except you can re-assign them. You can define a variable with the
var
keyword.
Methods
Methods are defined with the def
keyword.
def add(x: Int, y: Int): Int = x + y
println(add(1, 2)) // 3
A method can take multiple parameter lists:
def addThenMultiply(x: Int, y: Int)(multiplier: Int): Int = (x + y) * multiplier
println(addThenMultiply(1, 2)(3)) // 9
The last expression in the body is the method’s return value. (Scala does have a return
keyword, but it is rarely used.
def getSquareString(input: Double): String = {
val square = input * input
square.toString
}
println(getSquareString(2.5)) // 6.25
Classes
class Greeter(prefix: String, suffix: String) {
def greet(name: String): Unit =
println(prefix + name + suffix)
}
The return type of the method greet
is Unit
, which signifies that there is nothing meaningful to return. It is used similarly to void
in Java and C.
Last updated
Was this helpful?