https://kotlinlang.org logo
Join Slack
Powered by
# stdlib
  • 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
  • l

    louiscad

    05/21/2025, 12:15 PM
    Hello! Is there an allocation-free, KMP equivalent of Java's
    System.nanoTime()
    ? I want to measure small things (at high frequency), without the measurement affecting the measurement too much.
    Clock.System.now()
    returns a newly allocated
    Instant
    , and
    TimeSource.Monotonic.markNow()
    returns a value class wrapping
    ValueTimeMarkReading
    , which I think is also not just a primitive but a full allocated object. And
    measureTime
    uses the latter function…
    👀 2
    ➕ 2
  • z

    Zoltan Demant

    05/30/2025, 2:15 PM
    Any way to make this work? 🙂
    Copy code
    package aggregate.common
    
    abstract class Keyed(
        val key: String,
    ) {
        // Does not compile, Id is value class that wraps String 
        constructor(id: Id) : this(
            key = id.value,
        )
    
        constructor(keyed: Keyed) : this(
            key = keyed.key,
        )
    }
    c
    p
    +2
    • 5
    • 28
  • c

    CLOVIS

    06/04/2025, 8:32 PM
    Are there plans to make
    Uuid
    and
    Instant
    @Serializable
    ?
    e
    h
    • 3
    • 9
  • e

    Eugen Martynov

    06/06/2025, 3:40 PM
    I wonder why we don't have
    Uuid.parseOrNull()
    c
    • 2
    • 1
  • s

    Slackbot

    06/06/2025, 4:25 PM
    This message was deleted.
    k
    e
    • 3
    • 2
  • z

    Zoltan Demant

    06/09/2025, 3:55 AM
    I keep getting warnings about
    timestampOffset
    always being 0 here, but its not the case. Compiler bug?
    Copy code
    var minTimestamp: Long? = null
    var maxTimestamp: Long? = null
    
    journal.trainings.fastForEach { training ->
        val timestamp = training.timestamp.millis
    
        minTimestamp = minTimestamp?.coerceAtMost(timestamp) ?: timestamp
        maxTimestamp = maxTimestamp?.coerceAtLeast(timestamp) ?: timestamp
    
        ..
    }
    
    val timestampOffset = minTimestamp ?: 0L
    val timeSpan = (maxTimestamp ?: timestampOffset) - timestampOffset // "Value of 'timestampOffset' is always zero"
    j
    d
    • 3
    • 2
  • z

    Zac Sweers

    06/09/2025, 1:03 PM
    Why doesn't
    sortedSetOf()
    return
    SortedSet
    ? Currently it returns
    TreeSet
    , which isn't wrong but feels like it's an unnecessary implementation detail exposure edit: found https://youtrack.jetbrains.com/issue/KT-20972
    👆 1
    👆🏻 1
  • d

    Derek Peirce

    06/13/2025, 5:46 AM
    Has it ever been considered to allow concatenation of `Regex`es that contain different options? A decent number of times, I've had a case where I want to build a regex that is composed mostly of constants, but with a lot of characters that would require escaping. For a very simplified example, it would be very handy if, instead of:
    Copy code
    Regex("""java\.lang\.ArrayIndexOutOfBoundsException: Index \d+ out of bounds for length \d+""")
    I could write:
    Copy code
    Regex("java.lang.ArrayIndexOutOfBoundsException: ", RegexOption.LITERAL) + Regex("""Index \d+ out of bounds for length \d+""")
    r
    e
    • 3
    • 3
  • r

    Raid Xu

    06/13/2025, 7:07 AM
    Hi, I'm wondering why
    ReentrantReadWriteLock.write
    in
    Locks.kt
    is marked as
    InlineOnly
    . Is it to forbid Java from calling it? But what's reason behind it?
    d
    d
    • 3
    • 2
  • m

    Marcin Wisniowski

    06/25/2025, 1:40 PM
    listOf(1, 2, 3).containsAll(listOf(2, 2))
    returns true. What's the best alternative that will tell me correctly that the first list doesn't, in fact, contain all the elements of the second list? I want to consider the amount of items.
    j
    k
    • 3
    • 11
  • e

    Eugen Martynov

    07/02/2025, 12:11 PM
    Why
    Long.toHexString()
    produces a different string comparing to Java one? There are extra
    0
    padding
    k
    • 2
    • 5
  • z

    Zoltan Demant

    07/03/2025, 11:27 AM
    Can someone explain to me how this is possible? I mean, it makes sense, A and B are different types, but theyre still value classes.
    Copy code
    sealed interface BranchIdentifier {
        val key: String
    }
    
    @JvmInline
    value class A(override val key: String) : BranchIdentifier
    
    @JvmInline
    value class B(override val key: String) : BranchIdentifier
    
    fun main() {
        val collection = mutableSetOf<BranchIdentifier>()
        collection.add(A("5"))
        collection.add(B("5"))
        println(collection.size) // Prints 2
        println(collection.contains(A("5"))) // true
        println(collection.contains(B("5"))) // true
        println(collection.remove(A("5"))) // true
        println(collection.contains(B("5"))) // true
        println(collection.size) // 1
    }
    j
    e
    +2
    • 5
    • 16