Skip to content
Learn Netverks

Lesson

Step 23/36 64% through track

delegation

Delegation

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Delegation: the syntax, patterns, and safety habits you need before advancing in Kotlin.

Teams still ship Delegation in Kotlin codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Delegation in contexts like: Android apps, Spring services, and shared KMP modules.

Write Kotlin in main.kt with fun main(), click Run on server—the dev runner kotlinc compiles to a JVM jar and java runs it; use println for output (requires JDK + kotlinc; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Kotlin supports class delegation with the by keyword—forward interface implementations to a delegate object, reducing boilerplate versus manual forwarding in Java. Property delegation uses by lazy, by lazy(LazyThreadSafetyMode), and custom delegates.

Class delegation

interface Repository {
    fun find(id: String): String
}

class CachedRepo(private val inner: Repository) : Repository by inner

The compiler generates forwarders for interface members you do not override.

Property delegation

val config by lazy { loadConfig() } computes once on first access—common for expensive initialization.

Important interview questions and answers

  1. Q: Class delegation vs inheritance?
    A: Delegation composes behavior without subclassing the implementation—favor composition for decorators.
  2. Q: lazy thread safety?
    A: Default lazy is synchronized; use LazyThreadSafetyMode.NONE when single-threaded.

Self-check

  1. What keyword implements interface delegation?
  2. When does lazy initialize its value?

Tip: by lazy is thread-safe by default—pick LazyThreadSafetyMode when you know single-thread use.

Interview prep

class delegation by?

Forwards interface to composed object—built-in pattern.

lazy delegate?

Thread-safe lazy initialization on first access.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • by lazy when?
  • Delegated properties?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump