https://kotlinlang.org logo
Join Slack
Powered by
# getting-started
  • 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? 🤔
    ➕ 5
    v
    a
    • 3
    • 5
  • 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
    • 3
  • 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
  • m

    min

    09/20/2025, 12:26 PM
    Is there a quick introductory writeup on Kotlin compiler extensions? It’d be great if the article covered what they can and can’t do, the general structure of them, and such. I want to know if you can use an extension to add new syntax, or all code has to use valid existing syntax whether it’s processed by the extension later or not, how much the input code can be altered by the extension, and so on
    c
    y
    • 3
    • 3
  • a

    AndreyVanDenHaag

    09/23/2025, 6:07 AM
    Hi All, if I have a Map<String, String>, is there a way to automatically create a data class with fields like Int, Double, Boolean. (At the moment I have to create tons of code with very basic conversions.)
    g
    s
    s
    • 4
    • 33
  • s

    Slackbot

    09/29/2025, 1:51 PM
    This message was deleted.
    🧵 1
    t
    • 2
    • 1
  • s

    Slackbot

    09/29/2025, 1:51 PM
    This message was deleted.
    🧵 2
    g
    l
    • 3
    • 2
  • y

    Youssef Shoaib [MOD]

    10/03/2025, 2:24 AM
    Is there a way for me to clear caches for only one Kotlin file? Sometimes the IDE plugin goes crazy, and I have to do a full Invalidate+Restart, but I wish I could do it only for the file it's freaking out on
    a
    • 2
    • 3
  • k

    Klitos Kyriacou

    10/03/2025, 11:00 AM
    Is there any YouTrack issue to make the compiler allow the following, or is there a reason it can't?
    Copy code
    fun foo(n: Int): Int {
        require(n >= 1 && n <= 3)
        return when (n) {
            1 -> 10
            2 -> 20
            3 -> 30
        }
    }
    h
    h
    +3
    • 6
    • 10
  • j

    Joshua Hansen

    10/03/2025, 10:52 PM
    Is it possible to suppress deprecation warnings without doing it for the entire file? When I try to suppress a usage in a top-level function, it says "redundant suppression" and the import statement still has the deprecation warning.
    Copy code
    import com.whatever.DeprecatedClass <-- Deprecation warning persists
    
    @Suppress("deprecation") <--- redundant suppression
    fun test(value: DeprecatedClass) { ... }
    j
    e
    m
    • 4
    • 5
  • c

    Colton Idle

    10/09/2025, 8:07 PM
    I'm working on a library (an android library to be exact). if I update that lib to kotlin 2.2.20, would all of my consumers be forced to use that new version? like. is it better for me to use an old version?
    e
    t
    • 3
    • 5
  • s

    Sudarshan

    10/15/2025, 2:19 PM
    Hi everyone! This is Sudarshan. I’m reaching out to share a serious problem I’m facing. I belong to a community of students where most people are only familiar with Java, JavaScript, Python, C, and C++. It’s really hard to find someone who knows Kotlin. In fact, I was talking with one of my professors at college, and when she saw Kotlin mentioned in my resume, she said she had never heard of it before. Well, it’s not rare to find someone in tech who doesn’t know about Kotlin—but I want to change that. To make a difference, I’ve decided to approach different colleges in my city and give talks on Kotlin and Kotlin Multiplatform. I believe that spreading awareness about Kotlin will help increase its adoption and possibly make it even more popular than Java. I’m not sure if this is the right place to talk about it, but am I thinking in the right direction?
    j
    j
    +2
    • 5
    • 15
  • 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
    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
    • 3
    • 50