Sunday, September 26, 2021

Kotlin tips and tricks...

0_Unsorted_

Read more: official reference and meta programming

Optional parameters for class:

class Yuh(optionalParameter: String = "" )

If optionalParameter is not passed, it equals to "" by default.

How to pass a class as a parameter

val c = MyClass::class
goToActivity(OneMainActivity::class.java)

How to get a class of an object

var classOfMyObject = myObject!!::class.java

(yep, in Kotlin .java is to be added for some reason, at least that option works for me, even though the class of the variable is a Kotlin class not the Java one)

Ternary operator

Execution:

if(expressionAInBrackets) expressionB else expressionC

Assignment:

var v = if (a) b else c

How to iterate through the class properties

MyClass::class.memberProperties.forEach {
log("name ${it.name}: = ${it.get(objectOfMyClass)}")
}

Kotlin operators to manage nullable values and types: ?, ??, !, !! 

Official Kotlin reference is here

Safe call

Safe call on the left side of expression:
println(b?.length)

This returns b.length if b is not null, and null otherwise. 

Safe call on the right side of expression:

person?.department?.head = managersPool.getManager()

If either `person` or `person.department` is null, the function is not called.

No comments:

Post a Comment