https://kotlinlang.org logo
Join SlackCommunities
Powered by
# stdlib
  • e

    Eugen Martynov

    10/11/2024, 12:01 PM
    Related to topic above - would it be useful to have
    Boolean?.orFalse()
    ?
    e
    c
    +2
    • 5
    • 7
  • g

    groostav

    10/23/2024, 4:18 AM
    I don't suppose the kotlin team has any interest in creating multiplatform file permission manipulation? I'm trying to change the permissions on a path created in oracle java-21
    Files.createDirectories
    . They have their
    PosixFileAttribute
    stuff which makes it elegant enough (still pretty ick) for linux... but you're SOL on windows. We do a fair bit of native code stuff here so I figured I'd hit JNA's nice Win32 wrapper to see if I could write some native bindings to do it myself... https://learn.microsoft.com/en-us/windows/win32/secauthz/modifying-the-acls-of-an-object-in-c-- microsoft's sample code does not give me hope. It contains a
    goto
    . But this does make me wonder what IDEA does itself, being a kotlin/java app and --im sure-- having a bunch of argument with file access rights.
    j
    f
    • 3
    • 6
  • t

    Thomas

    10/23/2024, 6:28 AM
    Is there any reason why there is no:
    Copy code
    fun <T> List<T>.slice(fromIndex: Int, toIndex: Int): List<T>
    but only:
    Copy code
    fun <T> List<T>.slice(indices: IntRange): List<T>
    k
    • 2
    • 5
  • l

    LeoColman

    10/27/2024, 3:32 PM
    Copy code
    internal fun Iterable<*>.containerName(): String {
       return when (this) {
          is List -> "List"
          is Set -> "Set"
          is Map<*, *> -> "Map"
          is ClosedRange<*>, is OpenEndRange<*> -> "Range"
          is Collection -> "Collection"
          else -> "Iterable"
       }
    }
    Why does this code compiles when
    Map
    and
    Ranges
    are not Iterable? AI caught this issue for me and I expected the compiler to 😂
    y
    o
    +2
    • 5
    • 8
  • h

    holgerbrandl

    10/31/2024, 3:23 PM
    Hey there, is there a stdlib function to chunk a list by an attribute which is changing? Something along
    Copy code
    fun <T, K> List<T>.chunkBy(selector: (T) -> K): List<List<T>> {
        val result = mutableListOf<MutableList<T>>()
        var lastKey: K? = null
        for (item in this) {
            if (selector(item) != lastKey) result.add(mutableListOf(item)).also { lastKey = selector(item) }
            else result.last().add(item)
        }
        return result
    }
    
     data class Person(val age: Int)
    
    val persons = listOf(Person(23), Person(12), Person(23), Person(23), Person(22))
    val chunkBy = persons.chunkBy { it.age }
    but maybe its already part of stdlib?
    j
    a
    k
    • 4
    • 10
  • a

    Arthur Krukowski

    11/08/2024, 3:47 PM
    Hi, guys. In our project, we use KMP with JVM and JS targets. After testing a migration to Kotlin 2.0, we encountered crashes when running the JS target. Our research led us to LinkedHashMap (MutableMap has the same behavior). It appears that after calling the Iterator#remove method, the entry's key and value fields can be set to null. Here’s a simple test case to reproduce:
    Copy code
    @Test
        fun test1() {
            val map = LinkedHashMap<String, Int>()
            val n = 3
            repeat(n) {
                map["$it"] = it
            }
    
            println(map)
            val iterator = map.iterator()
            var count = 0
            while (iterator.hasNext()) {
                val entry = iterator.next()
                iterator.remove()
                println("${entry.key}=${entry.value}")
    //            assertEquals(count++, entry.value)
            }
        }
    We got next results: JVM (on all versions):
    Copy code
    {0=0, 1=1, 2=2}
    0=0
    1=1
    2=2
    JS (Kotlin 1.9.24). Keys are null:
    Copy code
    {0=0, 1=1, 2=2}
    null=0
    null=1
    null=2
    JS (Kotlin 2.0.21). Keys and values are null:
    Copy code
    {0=0, 1=1, 2=2}
    null=null
    null=null
    null=null
    JS (Kotlin 2.1.0-RC). Throws exception when accessing entry after the remove method is called.
    Copy code
    ConcurrentModificationException: The backing map has been modified after this entry was obtained.
    In version 2.1.0-RC , at least we encounter a crash on JS that could serve as a hint for developers. Do we mention about this somewhere in documentation? And should the behavior be consistent among platforms? I mean, it looks like we crash only on JS, but not on JVM. Is it expected behavior for now?
    a
    • 2
    • 4
  • k

    Klitos Kyriacou

    12/03/2024, 4:54 PM
    One of the known problems with data classes is that it's easy to get destructured components in the wrong order. It doesn't make it easy when there is inconsistency in the stdlib:
    Copy code
    for ((index, value) in list.withIndex())  // Correct: the class name is IndexedValue: index first, value second.
    
    val (time, value) = measureTimedValue { } // Wrong! the class name is TimedValue, yet it's actually value first, time second.
    😬 2
    s
    p
    +4
    • 7
    • 6
  • k

    kevin.cianfarini

    12/29/2024, 6:15 PM
    Any chance we can have
    Double.toString(decimals: Int)
    as a publicly available function? It seems to already be implemented as part of
    Duration
    . https://github.com/JetBrains/kotlin/blob/rrr/2.1.0/core-docs/libraries/stdlib/src/kotlin/time/Duration.kt#L1058
    e
    • 2
    • 2
  • m

    MiSikora

    01/04/2025, 1:29 PM
    Is there an equivalent of
    java.lang.Character.isLetter(int codePoint)
    in Kotlin? I'm getting a warning when importing
    j.l.Character
    but I don't think there are functions operating on code points.
    ➕ 1
    m
    r
    +2
    • 5
    • 6
  • k

    kevin.cianfarini

    01/06/2025, 5:27 PM
    Is there a KEEP anywhere for how Kotlin plans to handle wider numeric types once the JVM supports them with Valhalla? Eg. 128 bit integers or 80 bit floating point numbers. See: https://mail.openjdk.org/pipermail/valhalla-dev/2024-June/012571.html
    ➕ 1
    • 1
    • 1
  • k

    kevin.cianfarini

    01/15/2025, 7:16 PM
    I’m curious to get some feedback from the people who designed
    Duration
    . Based on this comment in the KEEP, it seems that the initial desire to model a duration as a single
    Double
    wasn’t sufficient because of precision issues, and that’s why duration now sacrifices a bit for either nano or millisecond representation. > While storing a duration value as a
    Double
    number provides accuracy enough for practical purposes for both very short and very long durations, it may still feel unfortunate that adding or subtracting one nanosecond to/from a duration
    d
    slightly more than a hundred days resulted in rounding so that the result was equal to the same
    d
    . If you were to reflect on this decision, would you make it again? Specifically, would you design Duration as a value class again? Or would it be better to design Duration like Java with two values — a
    Long
    number of seconds and an
    Int
    number of nanoseconds? I’m asking because I am the author of alchemist which is heavily inspired by Duration. I’m working through some precision issues in my library and I’m wondering if the value proposition of a value class here is worth it to sacrifice an order of magnitude’s worth of precision like Duration does with nanos and millis.
  • k

    Klitos Kyriacou

    02/07/2025, 2:17 PM
    Is there any chance the new
    Uuid
    class can be made to support UUID v7?
    j
    h
    • 3
    • 3
  • o

    Olaf Gottschalk

    02/10/2025, 4:02 PM
    Question to the stdlib pros: why is there no extension function
    Number.toBigDecimal()
    ? I struggle with this a lot as there are specific functions
    Int.toBigDecimal()
    and so on, even for the real tricky cases like
    Double.toBigDecimal()
    which does the "right" thing using the String constructor of
    BigDecimal
    rather than the double constructor which may lead to real spooky results... So in my code, I write my own extension function:
    Copy code
    fun Number.toBigDecimal(): BigDecimal = when(this) {
        is Short -> this.toBigDecimal()
        is Int -> this.toBigDecimal()
        .......
    }
    This is highly repetitive and error prone... so, why is this function just missing from the standard lib?
    y
    k
    • 3
    • 7
  • y

    Youssef Shoaib [MOD]

    02/12/2025, 7:34 PM
    I might've asked this exact question before, so apologies. Why is the internal encoding of
    Result
    the way that it is? There is a potentially more efficient encoding where you leave failures unboxed, leave most successes unboxed, and only box successes that happen to be throwable. In other words, having the internal encoding be a union of
    Throwable | (R - Throwable) | SuccessfulThrowable<R>
    j
    • 2
    • 7
  • t

    Thomas

    02/13/2025, 6:17 AM
    Why doesn't
    KInterface
    exist in
    kotlin.reflect
    ? Its interesting that
    KClass
    has a boolean property
    isFun
    , that shows whether the class is a functional interface... Could this be related?
    e
    • 2
    • 1
  • d

    diego-gomez-olvera

    02/18/2025, 11:53 AM
    hello, everyone! I am curious to know when Base64 will stop being a
    @ExperimentalEncodingApi
    . I created some time ago a wrapper for android.util.Base64 which uses Java Base 64 for JVM tests and I wonder if I could fully replace it with the Kotlin version for KMP compatibility without having to change it later
    f
    • 2
    • 2
  • p

    PHondogo

    02/19/2025, 6:20 PM
    Is there any resource where i can watch for stdlib release notes history?
    f
    • 2
    • 1
  • r

    Rohde Fischer

    02/21/2025, 10:05 AM
    is it possible to design a recursive default function on an interface to operate on the super type until it "hits" itself? I'm thinking something like this (semi-pseudocode):
    Copy code
    interface Foo {
        val selfValue: String
    
        fun doSomething(): String {
            if (this::class == Foo::class) {
                return "Foo"
            } else {
                return "${super.doSomething()}.$selfValue"
            }
        }
    }
    j
    c
    • 3
    • 3
  • k

    Klitos Kyriacou

    02/21/2025, 1:56 PM
    The Java API has a constructor that allows you to pass an initial String or CharSequence to initialize it with a sensible initial capacity, e.g.:
    Copy code
    val str = StringBuilder("The value of your purchase is ").apply {
        ...do things...
        append(things)
    }.toString()
    This would be neater if
    buildString
    had an overload that takes a
    String
    or
    CharSequence
    parameter. Without it, we would have to do the above, or the even worse:
    Copy code
    val str = buildString("The value of your purchase is ".length + 16) {
        append("The value of your purchase is ")
        ...do things...
        append(things)
    }
    Has anyone ever made a request for such a function and what was the outcome?
    j
    • 2
    • 2
  • g

    George

    03/04/2025, 4:30 PM
    Hello folks, I am trying to benchmark the sequence API vs the stream API vs simple transformations. I am seeing some weird results that the stream API is always the slowest no matter the scenario (even for short circuit). Here is the repo: https://github.com/GeorgePap-719/StreamAllocationBenchmark
    f
    h
    • 3
    • 6
  • c

    CLOVIS

    03/22/2025, 10:11 AM
    Could we get a
    TreeMap
    in the standard library?
    ➕ 2
    e
    • 2
    • 6
  • j

    Javier

    03/23/2025, 1:27 PM
    With the new atomic types in the stdlib, is it still necessary to apply the atomicfu plugin? I guess the one from
    kotlin
    and not the one from
    Kotlinx
    is still necessary.
    y
    f
    • 3
    • 2
  • k

    Klitos Kyriacou

    04/02/2025, 12:04 PM
    We have a sum function for all the primitive types, but not for `BigDecimal`:
    Copy code
    listOf(1, 2, 3).sum()
    listOf(1.toBigDecimal(), 2.toBigDecimal()).sum()  // Error
    listOf(1.toBigDecimal(), 2.toBigDecimal()).sumOf { it }  // OK
    Since there is already a
    sumOf
    function specialized for
    BigDecimal
    , why isn't there a
    sum
    function for it too?
    ➕ 4
    h
    g
    • 3
    • 2
  • g

    ghedeon

    04/19/2025, 5:22 PM
    Is my guess correct, that there is no left/right versions of binary search in kotlin that can deal with duplicates, the way it's supported in python (
    bisect_left
    ,
    bisect_right
    )? Sad java Collections legacy
    k
    • 2
    • 1
  • c

    CLOVIS

    04/19/2025, 5:45 PM
    I'm surprised there isn't a
    IntRange.size
    … Am I missing something?
    h
    h
    • 3
    • 2
  • e

    Eugen Martynov

    04/20/2025, 12:26 PM
    Wonder why standard library doesn’t have binarySearch variant for arrays?
    c
    d
    k
    • 4
    • 9
  • v

    Vasily

    04/21/2025, 12:14 PM
    `Flow`s have a wonderful catch extension, and I wonder if a similar functionality could be added to `Sequence`s? The following implementation appears to work as expected:
    Copy code
    fun <T> Sequence<T>.catch(action: suspend SequenceScope<T>.(Throwable) -> Unit): Sequence<T> {
        return sequence {
           try {
              forEach { yield(it) }
           } catch (t: Throwable) {
              action(t)
           }
        }
    }
    Is the implementation correct? If so, could it be added to stdlib?
  • c

    CLOVIS

    04/25/2025, 9:58 PM
    The bitwise
    and
    or
    or
    operators are in package
    kotlin.experimental
    ? 🤔 https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.experimental/and.html
    t
    a
    j
    • 4
    • 4
  • l

    louiscad

    04/28/2025, 12:18 PM
    Hello, is there a reason we got new
    AtomicLong
    and friends in Kotlin 2.1.20, but still no KMP-compatible
    Lock
    ? I have a use case where I need to ensure a
    Map
    is edited with no concurrent modifications, and using
    kotlinx.coroutines.sync.Mutex
    has undesired consequences on the exposed API, and is also overkill.
    f
    • 2
    • 1
  • k

    Klitos Kyriacou

    04/28/2025, 5:21 PM
    I noted that in C#, the following LINQ code:
    Copy code
    veryLargeList.Order().Take(10).ToList();
    Does a Quickselect/partial Quicksort to avoid having to sort the entire array. Is there any chance that Kotlin Sequences can be optimized in the same way?
    Copy code
    veryLargeList.asSequence().sorted().take(10).toList()
    y
    k
    • 3
    • 4