Key Concepts Flashcards
Summary key/unique Kotlin concepts
Ranges
An interval that has a:
- start value
- end value
Common options for defining an interval:
- step(n)
- reversed()
val aToZ = “a”..”z”
val containsC = “c” in aToZ
1..9
val countDown = 100.downTo(0)
val rangeTo = 1.rangeTo(30)
val oddNumbers = rangeTo.step(2)
val countDownEvenNumbers s = (2..100).step(2).reversed()
String Templates
Embed values, variables, or expressions inside a string
without pattern replacement or string concatendation
—————————————————————————————–
“Hello $firstName”
“Your name has ${name.length} characters”
Loops
while(true)
for (k in list)
Equality
referential
- structural
- ————————————–*
val sameReference = a === b
val structuralEquality = a == b # == is null safe # calls .equals() on each object
Current Receiver
The object reference referred to
by the this keyword
—————————————————
- object to the left of the dot notation
- object of the class in which this function is defined
- OuterInstanceClass.this from nested classes
visibility modifiers
private
C only be accessed from the same file
protected
Visible only to other members of the class
or interface, including subclasses.
Cannot include top-level functions, classes or interfaces.
internal
Visible only from other classes, interfaces and functions
within the same IntelliJ, Maven or Gradle module.
control flow as expressions
The following control flow blocks are expressions,
versus statements:
- if…else
- try…catch
fun isTuesday() { // must include the else clause if (LocalDate.now().getDayOfWeek() == "TUESDAY") true else false }
val success = try {
readFile()
true
} catch (e: IOException) {
false
}
null syntax
val firstName: String? // allow null value
val firstsName: String = null // compile time error
val firstName: String? = anyThing is String // blows up if anyThing is null
val firstName: String? = anyThing is? String // safe
type checking
and casting
is
is?
smart casts
explicit casts
————————-
anyThing is String // will throw a runtime exception if anyThing is null
if (anyThing is String) {
println(anyThing.length)
}
when
- asdfasdf
- —————————————————-*
- only exhaustive when used as an expression
- what is the danger of the else clause ?