Expression
Expressions are computable statements1 + 1
Declare a value
val keywordval x = 1 + 1 ‘x = 3 // This does not compile.val x: Int = 1 + 1Declare a variable
var x = 1 + 1 x = 3 // This compiles because "x" is declared with the "var" keyword.
Anonymous function
Explain and write an example
(x: Int) => x + 1Function
Short explanation
Function with 0 param
Write example
val getAge = () => 32
Function with 1 param
Write example
val addOne = (x: Int) => x + 1
Function with > 1 params
Write example
val add = (x: Int, y: Int) => x + y
Method
def keyword.def add(x: Int, y: Int): Int = x + yMethod with 1 param list
Write example
def add(x: Int, y: Int): Int = x + y
Method with > 1 param lists
Write example
def addThenMultiply(x: Int, y: Int)(multiplier: Int): Int = (x + y) * multiplier
Method with 0 param list
Write example
def name: String = System.getProperty("user.name")
Methods with multi-line expressions
Write example
def getSquareString(input: Double): String = {
val square = input * input
square.toString
}Class
Write a class with a name, 2 params, and a method that doesn’t return any value
class Greeter(prefix: String, suffix: String) {
def greet(name: String): Unit =
println(prefix + name + suffix)
}Create a new instance of a class
Write example
val greeter = new Greeter("Hello, ", "!")
Case class
Explain
A special type of class that is primarily used to hold immutable data. It is designed to be used in functional programming and is often employed for modeling immutable data structures, such as records or data transfer objects (DTOs)
By default, instances of case classes are immutable, and they are compared by value (unlike classes, whose instances are compared by reference). This makes them additionally useful for pattern matching.
Define a case class
Write example
case class Point(x: Int, y: Int)
Instantiate a case class
Write example
val anotherPoint = Point(1, 2)You can instantiate case classes without the new keyword
Compare instances of case classes
Write example
if (point == anotherPoint) {
println(s"$point and $anotherPoint are the same.")
} else {
println(s"$point and $anotherPoint are different.")
} // Point(1,2) and Point(1,2) are the same.Instances of case classes are compared by value, not by reference
String interpolation
write example
val name = "Linh" print(s"Hello $name")
Keyword object
Definition
object is a singleton instance of a class. It is a way to define a single instance of a class directly, without needing to create an explicit instance.object MySingleton {
def sayHello(): Unit = {
println("Hello, I am a singleton object!")
}
}Access an object
By inferring to its name
val newId: Int = IdFactory.create()
Keyword class
Definition
new keyword.class Greeter(prefix: String, suffix: String) {
def greet(name: String): Unit =
println(prefix + name + suffix)
}Keyword trait
Definition
trait Greeter {
def greet(name: String): Unit
}trait Greeter {
def greet(name: String): Unit =
println("Hello, " + name + "!")
}