Programming Concepts Flashcards
When, if/else as an expression
The body must return a value but you don’t have to use return statement:
val name = if (condition) {
body 1
} else { condition
body 2
}
val name = when (parameter) {
condition 1 → body 1
condition 2 → body 2
condition 3 → body 3
}
Lambda expression
Shorthand syntax to declare function without fun keyword. You can store a lambda expression directly in a variable
val variableName ={
lambda expression
}
variableName () - to call it
?.
Save call operator
nullableVariable ?. method / property
Stops any attempt off member access to null references and return null
!!.
Not null assertion operator
nullableVariable!!. method / property
You assert that the value is not null
, - in when statement
To separate multiple conditions
condition 1, condition 2
in in when statement
in 1…10
is in when statement
To check the data type
is type → body 1
?:
Elvis operator to add default value when there is indeed null
val name = nullableVariable?.method ?: defaultValue
Class in Kotlin
ClassName {
Properties
Methods
Constructors
}
ClassName () - to create an object
ClassObj.methodName() - to call class method
Getter and setter functions
F.e.
var speakerVolume = 2
get () = field
set ( value ){
field = value
}
Variable read-only (val) don’t have set functions
Constructor
Primary - class can have only one, defined as a part of a class header
ClassName constructor() { body}
Secondary - class can have multiple with or without parameters. If the class have primary each secondary must implement it. Enclose in the class body
Open class
Informs the compiler that this class is extendable
Inheritance
SubclassName ( optional parameters) : superclass (optional parameters) {
Body
}
To override functions:
- in superclass: open fun
- in subclass override fun
this same can be used for properties
Super - to reuse superclass code in subclass
var objName : superClassName = subclassName () - object of subclass
Visibility modifiers
- public (default) accessible everywhere
- private accessible in the same class or source file
- protected accessible in subclass
- internal accessible in this same module
Modifier var name: date type = initial value
Modifier class name { body }
Module
A collection of source files and build settings that let you divide your project into discrete units of funcionality
Package
A directory or folder that groups related classes, a module can contain multiple packages