How by Lazy Works

Implement a simpler version of by lazy


2 minute read

by lazy is implemented by using the “property delegation” in Kotlin. But if you look into the source code and trying to understand what is going on, it can be confusing, because it is full of locks and generics and where’s the `getValue()`` function they say that the delegation must implement?? In the handmade spirit (best way to learn is by doing it yourself), let’s do a stripped down version ourselves.

Kotlin Noinline and Crossinline

What is noinline and crossinline?

Guowei Lv

4 minute read

Compile time constant const val NAME = "Guowei" fun main() { tv.text = NAME } After compile it will (almost) look like this: // Imaginary code fun main() { tv.text = "Guowei" } inline function We can do similar things to functions, by adding keyword inline. inline fun hello() { println("hello") } fun main() { hello() } So at compile time, the hello() function will be copied to the calling place:

Kotlin Time Dsl

A little time DSL in Kotlin

2 minute read

Often in project we want to declare some time constants, like companion object { const val INTERVAL = 5 * 60 // 5 minutes } This is fine, but can we do better in Kotlin? What I want is this 5 minutes in seconds or 8 days in hours, and it is not hard to achieve it actually. infix fun Number.daysIn(unit: TimeUnit): Long = daysFn(this, unit) infix fun Number.hoursIn(unit: TimeUnit) = hoursFn(this, unit) infix fun Number.

How to run, let, also, apply in Kotlin

A short summary on Kotlin standard library functions: run, let, also, apply

2 minute read

If you decide to write Kotlin code, eventually you will see a lot of usage of the following 4 functions from standard library: run, let, also and apply. After doing a lot of research, I show simple examples of how to use them here. First, a helper class Student. class Student(name: String, age: Int, stuNum: String) { var name = name private set var age = age private set var stuNum = stuNum private set fun increaseAge() { age++ } fun nameToUpperCase() { name = name.