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

    Vivek Modi

    10/16/2025, 7:22 AM
    Hey team, I was reading a few articles about Compose and View interoperability, and some people mentioned benchmarking to identify performance differences when using Compose within existing View-based screens. I haven’t done any benchmarking before, so I wanted to ask — what specific areas are usually measured in such cases? For example: • Rendering or layout inflation time • Frame rendering and jank rates • Recomposition or invalidation overhead • Memory and CPU usage differences Are there any other key metrics we should look at to pinpoint performance issues more accurately? Also, if you know any good learning resources, tools, or examples to understand how to write or run these benchmarks (especially for Compose), I’d really appreciate your suggestions. Thanks! 🙏
  • b

    Bernhard

    10/16/2025, 12:29 PM
    is there a way to make a constructor private and instead provide a constructor function? I need to capture a reified type
    Copy code
    inline fun <reified T : Any> createEvent(
        endpointTarget: String,
        id: String,
        type: String,
        payload: T,
    ) = Event(
        endpointTarget = endpointTarget,
        id = id,
        type = type,
        payload = payload,
        typeInfo = typeInfo<T>()
    )
    
    class Event<out T : Any> private constructor(
        val endpointTarget: String,
        val id: String,
        val type: String,
        val payload: T,
        val typeInfo: TypeInfo,
    )
    ✅ 1
    y
    p
    a
    • 4
    • 7
  • b

    Bernhard

    10/22/2025, 2:13 PM
    can anyone recommend something to generate code from openapi definitions? using the official openapi generator generates code that won't compile
    ✅ 1
    r
    s
    +2
    • 5
    • 17
  • j

    Joshua Hansen

    10/22/2025, 6:32 PM
    If I have something like this:
    Copy code
    class Foo {
        var number: Int = 0
    }
    Is it possible to pass a reference to the
    number
    property to another class so that the other class can reassign it?
    m
    s
    r
    • 4
    • 3
  • c

    CLOVIS

    10/22/2025, 6:46 PM
    I want to create a function that is
    inline fun <reified T> foo(): T
    . This function calls a function
    fun <T> impl(type: KType): T?
    . I want the behavior that: • If
    foo
    is called with a nullable type (e.g.
    foo<Int?>()
    ), then nulls can be returned. • If
    foo
    is called with a non-nullable type (e.g.
    foo<Int>()
    ), if
    impl()
    returns
    null
    then it throws an NPE. Is this possible? Usually I would use overloads when I have two functions that only differ from the nullability of their parameters/receivers, but I don't think this is possible when they only differ by return type?
    j
    y
    • 3
    • 8
  • k

    Kirill Grouchnikov

    10/22/2025, 7:12 PM
    For something like https://github.com/material-foundation/material-color-utilities/blob/main/kotlin/hct/Hct.kt#L158 which accepts a color as
    Int
    , passing in the encoded ARGB channels, is there a more "pleasant" way of replacing
    Hct.fromInt(0xFFFF0000u.toInt())
    with something closer to how it is in Java
    Hct.fromInt(0xFFFF0000)
    the trailing
    u.toInt()
    is just noise when I read this call. The only thing I can think of is adding my own
    fun Hct.fromLong
    extension to make it read better in Kotlin.
    j
    y
    • 3
    • 3
  • j

    Jakob

    10/24/2025, 2:48 PM
    Hi! I'm trying to use contracts but I don't entirely get it. My problem is I want to have the return value of a member function on a data class help the compiler infer something about a value of that data class, and I don't understand if this is actually doable with contracts or not. Here's a minimal example:
    Copy code
    data class TimeRange(
      val from: Instant,
      val to: Instant?,
    ) {
      fun isOpenEnded(): Boolean {
        return this.to == null
      }
    }
    Optimally, I'd like to be able to use this helper and have the compiler still correctly infer whether
    to
    is null or not. If I now add a method to check if a TimeRange ends later than another, it might look like this (it's logically incorrect but nevermind that for the sake of the example)
    Copy code
    fun endsLaterThan(other: Timerange): Boolean {
        return this.isOpenEnded() || (!other.isOpenEnded() && (this.to > other.to))
    }
    However, this code does not work as-is, the compiler gives me trouble about nullability. To my human eyes and brain it's clear that the final statement
    (<http://this.to|this.to> > <http://other.to|other.to>)
    is only reachable if neither
    <http://this.to|this.to>
    or
    <http://other.to|other.to>
    is
    null
    , since that would short circuit the boolean operations. The compiler does not infer this, so I thought I might be able to help it along using contracts! I have tried to add something like this, but it does not seem to work since I'm using
    implies
    to say something about a member of the receiver and not just the receiver itself?
    Copy code
    fun isOpenEnded(): Boolean {
      contract {
        returns(true) implies this.to == null
        returns(false) implies this.to != null
      }
    
      return this.to == null
    }
    If there's a way to make this work, I'd love to know! Links to reading material about contracts in general is also appreciated 👍
    d
    • 2
    • 1
  • j

    Jobby

    10/26/2025, 8:41 AM
    I'm not too experienced, especially when it comes to string processing in Kotlin. So sorry if this is a stupid Noob question. Here is the behavior I get and what I'm not really understanding: I have a simple text with six words in three lines separated by commas:
    Copy code
    Boo,Boo,Boo,Boo,Boo,Boo
    Foo,Foo,Foo,Foo,Foo,Foo
    Goo,Goo,Goo,Goo,Goo,Goo
    This is my code together with the output I get as comments.
    Copy code
    import java.io.File
    
    fun main() {
        val chars: String = File(
            "C:\\Work\\Kotlin\\test\\src\\main\\resources\\MyTest.txt"
        ).readText(Charsets.UTF_8)
        val lines = chars.split("\n")
        println("Number of Lines: ${lines.size}") // Number of Lines: 3
        println(lines[0])                         // Boo,Boo,Boo,Boo,Boo,Boo
        println(lines[1])                         // Foo,Foo,Foo,Foo,Foo,Foo
        println(lines[2])                         // Goo,Goo,Goo,Goo,Goo,Goo
        val myList1 = lines[0].split(",")
        val myList2 = lines[1].split(",")
        val myList3 = lines[2].split(",")
        println("myList1: $myList1")                // ]
        println("Number of Words: ${myList1.size}") // Number of Words: 6
        println("myList2: $myList2")                // ]
        println("Number of Words: ${myList2.size}") // Number of Words: 6
        println("myList3: $myList3")                // myList3: [Goo, Goo, Goo, Goo, Goo, Goo]
        println("Number of Words: ${myList3.size}") // Number of Words: 6
    }
    As you can see it only outputs myList3 correctly. myList1 and myList2 just output ']'. But if you look at the size, it seems like it processed my string correctly. And the thing is, this depends on which line is the last in the txt file. It just outputs the last line the way I'd expect, but not the previous ones. Why is that? Is this a bug? JDK: corretto-23.0.2 Ide: IntelliJ IDEA 2025.1.5.1 (Community Edition) - Build #IC-251.28293.39, built on September 2, 2025
    p
    r
    • 3
    • 7
  • s

    Shaun Wild

    10/26/2025, 2:59 PM
    Would it be unreasonable as a language feature, to give compiler hints on required fields to be set in type-safe builders? Also promotion of type-safe builder relevant properties, in the editor?
    j
    h
    d
    • 4
    • 14
  • p

    Pihentagy

    10/27/2025, 3:04 PM
    Given the following example, can one explain why
    when
    is uncomplete? https://pl.kotl.in/uwOMcC-Fd
    Untitled
    e
    • 2
    • 3
  • c

    CLOVIS

    10/27/2025, 8:07 PM
    I find very interesting that this code isn't ambiguous.
    Copy code
    import io.ktor.http.HttpStatusCode.*
    
    @Serializable
    private data class NotFound(val id: String)
    
    val f = foo<NotFound>(NotFound)
                |         |
                |         HttpStatusCode.NotFound
                data class NotFound
    y
    • 2
    • 2
  • y

    y

    10/29/2025, 2:25 PM
    I have
    fun <T> foo1(vararg elements: Iterable<T>) = /* ... */
    I also have
    fun foo2(vararg elements: List<Bar>)
    what exactly happens when I call
    foo1(*elements)
    from within
    foo2
    ? what does the spread operator do here? is this zero cost?
    y
    c
    • 3
    • 8
  • b

    Bernhard

    10/30/2025, 9:40 AM
    I'm trying to convert a while(x.hasNextPart()) loop into a sequence; so far I've found generateSequence but I'd need to bundle up the hasNext boolean so I can stop, e.g.
    generateSequence { Elem(it.hasNextPart())}.takeUntil {it.hasNext}
    is there a better way to do that? and in that case, would you prefer an Iterator instead?
    ✅ 1
    K 1
    j
    • 2
    • 3
  • g

    Gasan

    10/31/2025, 10:44 AM
    Dear all. Why does Kotlin force parameter variables to be constants,
    val
    ? Kotlin does not have a concept of a "pointer to a const", therefore I can change the referenced value, unless it is immutable. I mean,
    val
    parameter variable does not amount to much unless the referenced value is immutable.
    v
    s
    +4
    • 7
    • 60
  • u

    ursus

    11/01/2025, 12:50 AM
    When valhalla drops, I assume it will introduce new byte code, so kotlin compiler will need to be updated to emit such bytecode But what about android? I'd assume ART needs to implement such new bytecode -- does that mean the new true value classes will be bound to latest android version?
    e
    g
    • 3
    • 12
  • y

    y

    11/03/2025, 9:44 AM
    apologies in advance for the complexity here. trying to debug the following exception:
    Cannot invoke "java.util.Map.get(Object)" because the return value of "A.getMethods()" is null
    which we seem to get, but only sometimes. we have this: (
    A
    ,
    B
    ,
    C
    are all concrete classes, renamed to anonymize)
    Copy code
    abstract class A(/* ... */) : Lots, Of, Things {
        abstract override val methods: Map<B?, C>
        abstract override val someMethod: C?
        /* ... */
        override fun getMethods(): List<C> = methods.values + listOfNotNull(someMethod)
    }
    what could be the issue here? is it an order of initialization thing? is it related to the choice of the name
    getMethods
    ? (since kotlin desugars getters to that name, no?)
    s
    b
    h
    • 4
    • 7
  • c

    CLOVIS

    11/03/2025, 5:12 PM
    Is there any distinction, in Kotlin, between signalling and quiet NaNs?
    e
    • 2
    • 9
  • j

    Jack Boyce

    11/04/2025, 7:59 AM
    Hi, I'm an absolute beginner going through the Compose Multiplatform demo app. I got it to build and run for all of the targets except for Android, where I get the attached error message "please select Android SDK". Under File->Project Structure->SDKs I have Android API 36.0, extension level 17 installed. Is there somewhere else I'm supposed to set the Android SDK? Thanks!
    j
    • 2
    • 14
  • b

    Bernhard

    11/04/2025, 11:58 AM
    been working a bit with KTOR recently and it has a fantastic URL builder that feels like it should belong into the stdlib (or at least into a kotlinx lib)
  • h

    hfhbd

    11/05/2025, 11:14 AM
    Why is it possible to pass
    null
    in Map<String, String>.get(null):
    mapOf<String, String>("f" to "f").get(null as String?)
    r
    e
    • 3
    • 4
  • e

    Edgar Avuzi

    11/08/2025, 5:52 AM
    Hi everyone, For this problem: https://leetcode.com/problems/increasing-order-search-tree/, I’m trying to write a Kotlin solution that clearly separates the logic for tree traversal order from the logic for building the resulting linked list. I did that in other languages, but I’m struggling to come up with an elegant and gibberish-free Kotlin version that doesn’t feel awkward or verbose. Combined all solutions here https://gist.github.com/Sedose/1d0ee8a6717feeb28a17aaeb4ff89080. Would appreciate any suggestions for making it good looking
    y
    • 2
    • 3
  • e

    elect

    11/09/2025, 10:55 AM
    why if I use an unamed context parameter this isn't available for resolution?
    Copy code
    import org.gradle.api.Project
    import java.io.ByteArrayOutputStream
    
    context(_: Project)
    operator fun String.invoke(vararg args: String): String {
        val output = ByteArrayOutputStream()
        providers.exec { // error, `providers` unresolved
            commandLine("arduino-cli", "version")
            standardOutput = output
        }
        return output.toString()
    }
    y
    • 2
    • 7
  • r

    Rob Elliot

    11/09/2025, 11:09 AM
    Dependabot is trying to upgrade micrometer from 1.15.5 to 1.16.0 and my Kotlin is no longer compiling:
    Copy code
    fun nullableReturn(): String? = TODO()
    
    val timer: Timer = TODO()
    
    try {
      timer.recordCallable {
        nullableReturn()
      }
    } finally {
      timer.close()
    }
    > Argument type mismatch: actual type is 'CallableString?', but 'Callable<uninferred T! (of fun T : Any recordCallable)>!' was expected.
    • 1
    • 3
  • n

    Natalia Mishina

    11/10/2025, 12:42 PM
    kodee welcoming Hey everyone! If you’ve just started learning Kotlin (or are about to) — we’d love to hear from you! 💬 The Kotlin team is running a diary study to learn how developers onboard to Kotlin — what the first steps look like, what challenges come up, and what helps you make progress in the Kotlin ecosystem. 🗓️ The study runs for 3–4 weeks and includes: • an intro call (15–20 min); • a simple diary in Google Docs; • a debrief interview (~40 min). If this sounds like you, fill out this 👉 1-minute form to apply and book an intro call Thanks 🙂
    K 2
  • j

    Jérémy CROS

    11/10/2025, 3:59 PM
    Hi everyone 🙂 I'm looking to convert a callback from a 3rd party sdk we're using to a StateFlow and I can't for the life of me find something that works 😕 Code looks like that:
    Copy code
    class Provider {
    
        private val listener by lazy {
            object: 3rdPartyListener {
                // Bunch of callbacks
    
                // The one I actually care about
                override fun onError() {
                    // Spam errors when in errors, do nothing otherwise
                }
            }
        }
    }
    I've read about
    callbackFlow
    but I can't quite make it work. For the use case of a callback that spam error / do nothing, AI is suggesting using a
    debounce
    but I don't know, that seems weird... Any help / suggestions appreciated! 🙏
    t
    d
    l
    • 4
    • 5
  • l

    Lukasz Kalnik

    11/13/2025, 2:17 PM
    What is currently the most idiomatic way to check if a date (today) is between a range of dates, e.g. Nov 28th and Jan 6th (regardless of the year)?
    👍 1
    b
    j
    +3
    • 6
    • 26
  • j

    Joshua Hansen

    11/17/2025, 7:40 PM
    Very small annoyance but I still get a warning
    Assigned value is never read
    on
    aNumber += 1
    even with the suppressions. I personally consider this warning wrong but I'm sure people could argue about it. Is there anyway to suppress it? Also, why did the `Wrapped into a reference object to be modified when captured in a closure." statement go away?
    Copy code
    class Foo(val lambda: () -> Unit)
    
    @Suppress("UNUSED_VARIABLE", "UNUSED")
    fun test() {
        var aNumber = 0 // "Wrapped into a reference object..." doesn't show anymore
    
        val newFoo = Foo {
            val test = 1 + aNumber // Do something with current value
            aNumber += 1 // Change value to be used next time Foo.lambda() is called
        }
        // do something with newFoo here to use later like add it to a list, etc.
    }
    b
    d
    +2
    • 5
    • 7
  • p

    Pihentagy

    11/19/2025, 7:39 AM
    I have a project where incoming data is declared as a json schema. I'd like to generate dtos from the json schema on compile time. Can you recommend a library for that?
    s
    j
    • 3
    • 3
  • j

    Joshua Hansen

    11/19/2025, 7:25 PM
    Need some help with this one. I have a few objects which implement a generic interface and I have a list of those objects and I"m trying to work with a function. I can unsafe cast to get around this, but is there a method to achieving the same thing without this? Here is a simplified example:
    Copy code
    interface Test<T: Number> {
        val clazz: KClass<T> // Keep reference to the class so we can find the right one later
        fun foo(item: T)
    }
    
    // Int object:
    object A : Test<Int> {
        override val clazz = Int::class
        override fun foo(item: Int) {
            // do something
        }
    }
    
    // Double object
    object B : Test<Double> {
        override val clazz = Double::class
    
        override fun foo(item: Double) {
            // do something
        }
    }
    
    fun test() {
        // Working with a list of these objects
        val objs: List<Test<out Number>> = listOf(A, B)
        
        val myInt = 1
        
        // I'm certain find returns A, but due to forced out projection I get an error.
        val properObj = objs.find {
            it.clazz == myInt::class
        }
    
        properObj?.foo(myInt) // Receiver type 'Test<out Number>' contains out projection which prohibits the use of 'fun foo(item: T): Unit'.
    }
    c
    • 2
    • 1
  • m

    MrNiamh

    11/20/2025, 3:47 PM
    I have this simple example. Why does
    a
    compile fine, but
    b
    is a compilation error? I wouldn't expect
    a
    to compile but it does, but i'm also surprised it's not consistent between the two.
    Copy code
    data class ContactId(val value: UUID)
    
    fun main(){
        val contactId = ContactId(UUID.randomUUID())
        val uuid = UUID.randomUUID()
        val a = contactId == uuid
        val b = contactId.toString() == uuid
    }
    y
    • 2
    • 2