https://kotlinlang.org logo
Join Slack
Powered by
# getting-started
  • r

    robstoll

    08/25/2025, 9:43 AM
    can you define a context parameter for lambdas? something like
    Copy code
    foo(f: context(users: UserService) Bar.() -> Unit)
    👌 1
    h
    h
    • 3
    • 10
  • b

    bazbo.222

    08/25/2025, 4:24 PM
    Hey! I know Kotlin has lazy properties with its delegates feature. Is there any way to add lazy evaluation (or, equivalently for my use case, memoization) such that the first time I call
    foo(arg)
    ,
    foo(arg)
    gets calculated, but the second, third etc. times that I call
    foo
    after that,
    foo(arg)
    just returns the already computed, stored value. E.g. in Python, this exists in the form of the
    @Memoize
    operator, if anyone is familiar with that. Is there any way to achieve this in Kotlin or should I just implement the memoization mechanism myself.
    j
    y
    j
    • 4
    • 12
  • j

    Joshua Hansen

    08/25/2025, 10:55 PM
    Is it possible to access an extension property given this setup?
    Copy code
    fun main() {
        val book = Book("Kotlin Basics", List(10) { Page(it + 1) })
        
        val p = book.pages[4] // get the fullName from this scope given `book` and `p`?
    }
    
    
    class Book(val name: String, val pages: List<Page>) {
        val Page.fullName: String
            get() = "$name: Page $number of ${pages.size}"
    }
    
    class Page(val number: Int)
    y
    k
    • 3
    • 5
  • h

    Huib Donkers

    08/26/2025, 11:13 AM
    I suppose this is very niche..: Can I initialize class member `val`s from a lambda while also forbidding non-local returns in that lambda? • If I want to allow non-local returns, I can do this: playground example. Using the non-local return in this case actually triggers an error for kotlin 2 (not for 1.9.25), but for a different reason. It's easy to give an example where the non-local return is allowed also in kotlin 2. • marking the lambda
    crossinline
    , forbids the non-local return, but I can no longer initialize member `val`s from the lambda. I can initialize member `var`s, and local `val`s. See playground example here. I don't understand why initializing member
    val
    would no longer be possible. â—¦ When trying to initialize a member
    val
    kotlin 1.9.25 errors "Captured values initialization is forbidden due to possible reassignment" (is the contract not understood here?) and kotlin 2 errors "Initialization of captured member values must be inlined" (is it not inlined?)
  • y

    y

    08/26/2025, 11:37 AM
    hey, we're seeing
    Cannot invoke "java.util.Map.get(Object)" because the return value of foo() is null
    very naively:
    foo()
    is a Kotlin function which returns
    List<Bar>
    , so under what conditions could it even return null?
    h
    • 2
    • 3
  • p

    purezen

    08/26/2025, 1:27 PM
    I am following the course from google
  • p

    purezen

    08/26/2025, 1:27 PM
    I am running this code snippet:
    Copy code
    import kotlinx.coroutines.*
    
    fun main() {
        println("Weather forecast")
        delay(1000)
        println("Sunny")
    }
    c
    h
    j
    • 4
    • 3
  • p

    purezen

    08/26/2025, 1:28 PM
    But I am not seeing a delay between the two lines
  • p

    purezen

    08/26/2025, 1:28 PM
    How do I introduce delay between them ?
    🧵 5
    c
    • 2
    • 2
  • u

    Uberunix

    08/27/2025, 12:39 AM
    When asking Gemini why I couldn't access map keys with dot notation since they're so similar to objects, it told me that this notation is reserved for values that are known when the code is compiled. In contrast, subscript syntax is reserved for data that's only known as the program runs. Is this an accurate explanation?
    y
    k
    +2
    • 5
    • 11
  • u

    Uberunix

    08/27/2025, 2:24 AM
    In a similar vein of "why this not that," I'm not finding a compelling explanation for the differentiated uses of = and ->. Specifically in the contexts of single expression functions vs. lambdas. They're both predicates to their respective return statements, and as far as I can see, serve the same purpose. So why the distinction in form? Why not just use arrow syntax in both cases?
    y
    j
    • 3
    • 3
  • a

    Arjan van Wieringen

    08/30/2025, 9:16 AM
    There is not kotlinx-html where all the SVG elements are present?
  • v

    v79

    08/30/2025, 9:15 PM
    I'm looking for a text template engine, like Handlebars, but written in pure Kotlin multiplatform. The only one I've found is KorTE. Has anyone seen a handlebars or moustache implementation in kotlin?
  • j

    John Safwat

    09/01/2025, 12:27 PM
    hello i was recently search for how to publish Some KMP Packages to the community and how to index it in KLibs.io so i was wondering if any one can help
    m
    v
    • 3
    • 6
  • r

    Rob Elliot

    09/02/2025, 9:54 AM
    Just checking - in a when block like this:
    Copy code
    import java.time.Period
    
    fun Period.toDays() = when (this) {
      Period.ofYears(1) -> 365
      Period.ofMonths(1) -> 30
      else -> days
    }
    the check is an equality check, not an identity check, isn't it? I'm getting a compiler warning
    Identity-sensitive operation on an instance of value type 'Period' may cause unexpected behavior or errors.
    , but surely this is an equality check...
    • 1
    • 2
  • v

    Vampire

    09/03/2025, 5:09 PM
    Is there a way to resolve the "Overload resolution ambiguity" without having dedicated function names?
    Copy code
    fun <T : Any> foo(block: () -> T?) {}
    fun <T : Any> foo(block: () -> List<T>?) {}
    fun <K : Any, V : Any> foo(block: () -> Map<K, V>?) {}
    fun <T : Any> foo(block: () -> Set<T>?) {}
    foo { "foo" }
    foo { listOf("foo") }
    foo { mapOf("foo" to "bar") }
    foo { setOf("foo") }
    (And without casting the arguments, I mean that the right method is used automatically)
    r
    • 2
    • 5
  • v

    Vampire

    09/03/2025, 9:59 PM
    Shouldn't each of these pre-condition calls imply that
    foo
    is non-null? So why is the second
    foo
    call not working?
    Copy code
    fun foo(foo: Any) = null
    val foo: String? = null
    foo(foo)
    check(foo != null)
    require(foo != null)
    assert(foo != null)
    foo(foo)
    y
    h
    +2
    • 5
    • 17
  • s

    Slackbot

    09/04/2025, 5:41 AM
    This message was deleted.
    j
    • 2
    • 3
  • o

    Odinakachukwu Omaka-chukwu

    09/04/2025, 12:40 PM
    Copy code
    sealed interface RandomState {
        data object Empty: RandomState
    
        enum class Validity(val message: String): RandomState {
            Valid("Is valid"),
            Invalid("Is not valid"),
        }
    }
    
    fun foo(state: RandomState) {
        when(state) {
            RandomState.Empty -> Unit
            RandomState.Validity.Valid -> {
                showMessage(state.message)
            }
            RandomState.Validity.Invalid -> {
                showMessage(state.message)
            }
        }
    }
    Why is it not able to smart cast to
    RandomState.Validity.Valid
    and
    RandomState.Validity.Invalid
    ?
    h
    h
    • 3
    • 3
  • u

    ursus

    09/05/2025, 11:50 PM
    Copy code
    fun foo(): String {
        var local: String? = null
        if (local == null) {
            local = "hello"
        }
        return local // compiler still thinks nullable
    }
    Why doesn't this smart cast?
    r
    j
    j
    • 4
    • 4
  • d

    Dewan Tawsif

    09/07/2025, 4:26 PM
    Is there anyway to pass compiler flags for build.gradle.kts file? My use case requires context parameters which need to be enabled by a compiler flag.
    d
    v
    • 3
    • 3
  • a

    Aozen

    09/08/2025, 12:03 PM
    hi all first day here what should i do?
    d
    • 2
    • 1
  • f

    Fredrik Meyer

    09/10/2025, 6:27 AM
    I have an interface
    Gateway
    and a class parameter
    KClass<Gateway>
    . But when I pass an instance of
    KClass<GatewayImpl>
    , the compiler complains. Is there a way around this? Casting works, so something is correct.
    y
    r
    • 3
    • 3
  • h

    Hildebrandt Tobias

    09/10/2025, 7:56 AM
    Hey, I have a timestamp like this
    2025-09-02T10:59:38+02:00
    and at one point (envelope) I deserialize it as
    Instant
    with no problem. At another point (payload) I want to do the same but it doesn't work. I looked at the imports but both import
    kotlinx.datetime.Instant
    . But one does so from
    org.jetbrains.kotlinx:kotlinx-datetime
    and the other from
    org.jetbrains.kotlinx:kotlinx-datetime-jvm
    , with the latter not working. The only dependency I have in both my
    common
    and
    jvmBackend
    modules is
    org.jetbrains.kotlinx:kotlinx-datetime
    so I guess it selects which one to use by itself. What would be the best course of action to remedy this Problem? Edit: Seems like I have to use
    Instant.parse()
    , before I had the json serializer do it, since most payloads are json and a select few are plain strings, but before I had no problems just using the json parser for that and it allowed me to have a more generic approach for all messages.
    k
    • 2
    • 4
  • d

    df

    09/10/2025, 1:43 PM
    I'm trying to convert some of our existing Java classes to Kotlin using IntelliJ's built-in converter. Unfortunately, when I run the conversion I get the following error in the logs. I've already tried to reproduce the issue with a minimal setup, but so far without success. I'm hoping someone can, based on the error message, suggest where I should look next.
    Untitled
  • i

    igor.wojda

    09/10/2025, 4:48 PM
    👉 I've noticed that several Kotlin code completions seem to be missing. I don’t have exact examples right now, but starting about 1–2 months ago some intention actions (the fixes that usually help improve code) stopped showing up. Has anyone else experienced this? 🤔
    âž• 4
    v
    • 2
    • 4
  • j

    Joshua Hansen

    09/12/2025, 4:45 PM
    Today I learned this is valid. Does anyone have insight into why this is? To me, it seems extremely wrong and confusing to be able to assign a
    val
    at all somewhere other that its declaration site.
    Copy code
    class Test {
        private val test: String
        
        init {
            test = "Hello"
        }
    }
    c
    j
    +2
    • 5
    • 5
  • g

    Gasan

    09/17/2025, 5:02 PM
    Hi all. I want to use my immutable kotlin data class in tests in my java code. In tests I initialize my data class with different values. In java I cannot use default parameters of the copy method. Also it seems to me too expensive to create multiple copies of the object while initializing it: each modification produces a new value. Ideally, I would like to use a builder to generate the object I need. Are there any tools to automatically create such a builder from an immutable data class or do I have to write it myself? edit: essentially to generate a "mutable" version of my data class.
    e
    • 2
    • 9
  • j

    Joe

    09/17/2025, 11:12 PM
    huh, with kotlin 2.2.20, https://github.com/josephlbarnett/leakycauldron/blob/fe5e5514dd035c9e0eaae70c6fdb422170035cf1/graphql/src/main/kotlin/com/trib3/graphql/execution/LeakyCauldronHooks.kt#L49-L50 gives this warning:
    Copy code
    [WARNING] file:///home/jbarnett/workspace/tribe/leakycauldron/graphql/src/main/kotlin/com/trib3/graphql/execution/LeakyCauldronHooks.kt:50:30 This declaration overrides a deprecated member but is not marked as deprecated itself. Add the '@Deprecated' annotation or suppress the diagnostic.
    ... but gives no such warning in 2.2.10 (I mostly only care because
    -Werror
    ). it looks like it is marked deprecated itself unless I'm missing something? I can, of course, override the non-deprecated methods instead but wanted to understand what's going on.
    d
    • 2
    • 2
  • m

    min

    09/18/2025, 7:31 AM
    If
    this.getChildAt(0)
    returns
    View!
    should it always be guarded with an
    if
    like this?
    Copy code
    if (childCount > 0) {
        getChildAt(0) as? AndroidComposeView
    }
    Why can’t I just do
    getChildAt(0) as? AndroidComposeView
    for an
    AndroidComposeView?
    that is
    null
    if the
    View!
    was null?
    i
    m
    • 3
    • 2