Added to Scala Functions, ControlStructures, PatternMatching, Variables and add a new Options sheet
parent
01c11fe1c2
commit
d5e06fc20f
@ -0,0 +1,17 @@
|
||||
// Optional values
|
||||
val s: Option[Int] = Some(22)
|
||||
val n: Option[Int] = None
|
||||
|
||||
// Removing optional values from a collection
|
||||
val listOfOptions: List[Option[Int]] = List(Some(1), None, Some(2), None, None, Some(3))
|
||||
listOfOptions.flatten // returns List(1, 2, 3)
|
||||
|
||||
// Get the value out of an option
|
||||
Some(5).get // returns 5
|
||||
|
||||
// Handling None
|
||||
// BAD
|
||||
None.get // This will throw java.util.NoSuchElementException
|
||||
// GOOD
|
||||
None.getOrElse(1) // This will handle the exception and return 1
|
||||
|
@ -1,11 +1,21 @@
|
||||
// variables
|
||||
// variable
|
||||
// mutable
|
||||
var x = 5
|
||||
|
||||
// constant
|
||||
// value
|
||||
// immutable, evaluated once during compilation
|
||||
// GOOD
|
||||
val x = 5
|
||||
// BAD
|
||||
x=6
|
||||
x = 5
|
||||
|
||||
// lazy value
|
||||
// immutable, evaluated once but only when called
|
||||
lazy val x = 5
|
||||
|
||||
// definition
|
||||
// immutable, evaluated every time it is called
|
||||
def x = 5
|
||||
|
||||
// explicit type
|
||||
var x: Double = 5
|
||||
val x: Double = 5
|
||||
|
Loading…
Reference in New Issue