Scala Getting Started Flashcards
Expression
Expressions are computable statements1 + 1
Declare a value
- Use the
val
keywordval x = 1 + 1
‘ - Values cannot be re-assigned
x = 3 // This does not compile.
- The type of a value can be omitted and inferred, or it can be explicitly stated
val x: Int = 1 + 1
Declare a variable
- Variables are like values, except you can re-assign them.
- You can define a variable with the var keyword.
~~~
var x = 1 + 1
x = 3 // This compiles because “x” is declared with the “var” keyword.
~~~
Anonymous function
Explain and write an example
- Function that has no name.
(x: Int) => x + 1
- On the left of ` =>` is a list of parameters. On the right is an expression involving the parameters.
Function
Short explanation
- Function that has name.
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
- Methods look and behave very similar to functions but with differences.
- Defined with the
def
keyword. - Followed by a name, parameter list(s), a return type, and a body.
def add(x: Int, y: Int): Int = x + y
Method 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, ", "!")