Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read / interpret this Kotlin code effectively?

Tags:

kotlin

I know how to read/interpret Java code and I can write it. However being new to kotlin I find code like below hard to read. Perhaps I am missing key concepts in the language.

But, how would you go about interpreting this code? Where do you propose one to start reading it in order to understand this piece of code quickly and efficiently? Left to right? Right to left? Break down parameters first? Look at return values?

inline fun <T : Any, R> ifNotNull(input: T?, callback: (T) -> R): R? {
    return input?.let(callback)
}
like image 897
thelastchief Avatar asked Aug 05 '26 15:08

thelastchief


1 Answers

So, like Java this is a generic function. It has two type parameters T which is of type 'Any' ('Any' is like 'Object' in Java) and R. The input parameter is a nullable T, as denoted by the question mark. Nullable types mean that the value can be null. The other function parameter is a function that takes in a T (non nullable type) and returns R. The return type of the function is a nullable R. The body of the function says that if input is not null, call and pass that to the callback and return that value. If input is null, then null is what gets returned.

like image 106
Matt Berteaux Avatar answered Aug 07 '26 18:08

Matt Berteaux