Kotlin

repeat, also lateinit and isInitialized

admin by @admin ADMIN
5h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`repeat(n) { i -> ... }` for N-times loops where you don't care about index naming. `lateinit var` lets you declare a non-null var without initializing it — common for DI / framework injection.
Kotlin
Raw
class UserController {
    // Initialized later (by DI framework, Android lifecycle, etc.)
    lateinit var userService: UserService

    fun init(svc: UserService) {
        userService = svc
    }

    fun isReady(): Boolean = ::userService.isInitialized      // safe check

    fun doWork() {
        if (!isReady()) error("controller not initialized")
        // userService.greet(...)
    }
}

class UserService(val name: String)

fun main() {
    // repeat — for-loop without an index name
    repeat(5) { println("hello $it") }

    val c = UserController()
    println(c.isReady())                          // false
    c.init(UserService("alice"))
    println(c.isReady())                          // true

    // Accessing uninitialized lateinit throws UninitializedPropertyAccessException
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.