Kotlin: 10 things to remember
- String concatenation: Using $ operator and curly braces.
//Example 1: include a variable inside string
val x = 100
val str = "This is a $x string"
// Example 2: use it with array by enclosing expression in curly braces
val numArray = arrayOf(1, 2, 3)
val str = "My array size is ${numArray.size} and value is ${numArray())}"
//Example 3: evaluate an expression inside a string
var x = 9
println("The value is: ${if(x>10) "large" else "small"}")
2. open keyword:
By default, classes are final in Kotlin and can't be inherited. To extend a class, it should be declared open.
open class Base(s: String)
class Derived(s: String) : Base(s)
Methods and properties should also be declared open to be extended.
3. lateinit: Properties with non-nullable types should be initialized. Sometimes, you might have to initialize them later, so you should mark the property lateinit.
lateinit var myString: classA
4. lazy initialization: In Kotlin commonly lazy initialization means use of delegation function “lazy{}”. There are many delegation functions, and lazy is one of them.
lateinit vs lazy initialization:
i) lateinit apply only on reference type, lazy initialization we can have primitive types as well.
ii) lateinit applies only to var while lazy initialization apply only to val
5. Use of “?” operator: Variables can’t hold null values. To assign them null to a specific variable type, we have to use “?” operator.
val myStr: String? = null
6. Safe call operator “?.” : For checking whether the value is null or not.
val myStr1 = "xyz"
val myStr2: String? = null
myStr1.length //works fine
myStr2.length //this will give an error. we have to check for the null condition first
if(myStr2 != null) {
print(myStr2.length)
}
//instead of ding this we can use safe call operator
print(myStr2?.length)
This works for chain calls as well.
a?.b?.c?.d //returns null if any of the value is null
6. Elvis operator “?:” Instead of writing if expression, we can use the Elvis operator instead.
val a: Int = if(str != null) str.length else -1
//use of Elvis operator for the same
val a: Int = str?.length ?: -1
7. “!!” Operator: For nullable type to non-nullable type conversion, throws the null pointer exception if the value is null.
var x: String? = "xyz"
var y = x!!.length //x!! here will return a non null value here, NPE otherwise
8. Safe cast: Cast the value to a particular type using “as” or “as?”
val y: Int = a as Int
// or
val y: Int? = a as? Int
9. Scope functions: apply, let, with, run, also
All these functions execute the block of code on an object.
https://kotlinlang.org/docs/scope-functions.html#context-object-this-or-it
10. “it” operatorit
is used within a lambda that takes exactly one parameter, to refer to the parameter concisely without having to give it a name.
for(element: myList) {
println(element)
}
// instead we can use "it" as follows
myList.forEach{ println(it)}
//or
myList.map { println(it) }