Sunday, September 26, 2021

Kotlin tips and tricks...


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

How to get a class of an object

var classOfMyObject = myObject!!

(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


if(expressionAInBrackets) expressionB else expressionC


var v = if (a) b else c

How to iterate through the class properties

MyClass::class.memberProperties.forEach {
log("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:

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