https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
stdlib
  • m

    miha-x64

    06/06/2020, 10:18 PM
    stdlib, embrace codePoints!
    inline fun CharSequence.forEachCodePoint(
        start: Int = 0, end: Int = length,
        action: (index: Int, codePoint: Int) -> Unit
    ) {
        var i = start
        var codePoint: Int
        while (i < end) {
            codePoint = Character.codePointAt(this, i);
            action(i, codePoint)
            i += Character.charCount(codePoint)
        }
    }
    👍 2
    j
    m
    • 3
    • 5
  • l

    LeoColman

    06/07/2020, 9:01 PM
    Is there a particular reason that Array isn't an IterablE?
    l
    • 2
    • 1
  • b

    bod

    06/11/2020, 5:01 PM
    Hello, World! What would be the easiest way to get an "inverted" version of a Map (by that I mean the values become the keys and vice versa)?
    t
    n
    +2
    • 5
    • 10
  • r

    rrva

    06/24/2020, 1:57 PM
    Give me an elegant way to express “Is T1 more than 15 minutes ago” in Kotlin. Is anything happening at https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.time/ ? I am using ChronoUnit.MINUTES.between now, but thinking is there is something even more readable
    s
    g
    z
    • 4
    • 10
  • r

    rrva

    06/24/2020, 2:56 PM
    Is there something like https://api.dart.dev/stable/2.8.4/dart-core/Iterable/where.html which makes you express things better than with
    filter
    or
    filterNot
    ?
    d
    g
    a
    • 4
    • 8
  • r

    rrva

    06/25/2020, 7:11 AM
    Can I create a ExperimentalTime TimeMark from an OffsetDateTime using something like this or is it completely wrong usage/thinking around TimeSources?
    @OptIn(ExperimentalTime::class)
    class DateTimeSource(val time: OffsetDateTime) : AbstractLongTimeSource(unit = DurationUnit.MILLISECONDS), TimeSource {
        override fun read(): Long {
            return time.toInstant().toEpochMilli()
        }
    }
    i
    • 2
    • 4
  • h

    Hullaballoonatic

    07/05/2020, 9:33 PM
    fun <C : Comparable<C>> C.coerceAtMost(maxValue: C) = if (this > maxValue) maxValue else this
    fun <C : Comparable<C>> C.coerceAtLeast(minValue: C) = if (this < minValue) minValue else this
    fun <C : Comparable<C>> C.coerceIn(minValue: C, maxValue: C) = coerceAtLeast(minValue).coerceAtMost(maxValue)
    Also
    fun <C : Comparable<C>> min(vararg elements: C): C
    fun <C : Comparable<C>> max(vararg elements: C): C
    I'm a bit surprised these methods aren't part of stdlib of any languages i know of. Is there a reason I haven't considered?
    m
    • 2
    • 2
  • j

    Jamy

    07/06/2020, 11:55 PM
    Hello ! Why is it useful that toString can return a “null” string if it is applied to null? I may sound silly to you, but I didn’t know. As a result, I just passed some time looking for why
    val a = b?.c.toString()
    where
    b == null
    results
    a != null
    since in this case
    a == "null"
    . So to get what I want, I have to write
    val a = b?.c?.toString()
    . It’s not a problem, I just don’t understand the purpose.
    😐 3
    d
    m
    +2
    • 5
    • 5
  • l

    louiscad

    07/08/2020, 12:15 PM
    Would you use such functions?
    fun List<E>.subListAfterFirst(element: E): List<E>
    fun List<E>.subListAfterLast(element: E): List<E>
    They could also take a predicate instead of an element. Maybe there's already a good alternative that I didn't think of or found?
    b
    d
    • 3
    • 4
  • b

    bbaldino

    07/10/2020, 10:28 PM
    Is it possible to generically create an enum from an instance of
    KType
    (of the enum) and a string (of the enum value) ?
    d
    • 2
    • 2
  • d

    diego-gomez-olvera

    07/17/2020, 11:18 AM
    public fun <T> MutableList<T>.removeAll(predicate: (T) -> Boolean): Boolean = filterInPlace(predicate, true)
    
    private fun <T> MutableList<T>.filterInPlace(predicate: (T) -> Boolean, predicateResultToRemove: Boolean): Boolean {
        if (this !is RandomAccess)
            return (this as MutableIterable<T>).filterInPlace(predicate, predicateResultToRemove)
    
        var writeIndex: Int = 0
        for (readIndex in 0..lastIndex) {
            val element = this[readIndex]
        ...
            if (writeIndex != readIndex)
                this[writeIndex] = element
         ...
    }
    It seems
    CopyOnWriteArrayList.removeAll
    does not copy on write but mutates in place instead
    g
    • 2
    • 4
  • n

    nkiesel

    07/17/2020, 8:07 PM
    Should there be standard support to sort lists of Strings locale-dependant? Something like
    fun Iterable<String>.sortedWith(collator: Collator) = this.map { collator.getCollationKey(it) }.sorted().map { it.sourceString }
    i
    • 2
    • 2
  • d

    Daniele B

    08/08/2020, 8:02 PM
    what is the best way in the stdlib (without Java) to convert a number to a string with thousands separated by commas? e.g. “2029292” which becomes “2,029,292"
    d
    • 2
    • 2
  • n

    natpryce

    08/09/2020, 8:40 AM
    Q: Does the stdlib have an associate-like function that takes a function to merge elements with duplicate keys (similar to Collectors.toMap in Java Streams)?
    d
    • 2
    • 3
  • m

    Marc Knaup

    08/09/2020, 1:49 PM
    It’s confusing that
    Flow.toList()
    closes the Flow but
    Stream.toList()
    doesn’t close the Stream. Is that inconsistency intentional?
    d
    • 2
    • 6
  • d

    Daniele B

    08/10/2020, 4:06 PM
    I would like to format a Float to a String with 1 decimal, but I can’t find the way. If I write this:
    val myString = "%.1f".format(myFloat)
    it tells me that the function
    format
    doesn’t exist?
    g
    r
    • 3
    • 5
  • m

    Matteo Mirk

    08/13/2020, 8:56 AM
    Is there an equivalent of
    java.text.NumberFormat
    in Kotlin multi-platform stdlib? I can’t seem to find any…
    🇳🇴 3
    • 1
    • 1
  • f

    Fleshgrinder

    08/15/2020, 3:56 PM
    Any particular reason why
    buildList
    and friends are still experimental in Kotlin 1.4?
    m
    n
    • 3
    • 4
  • r

    rrva

    08/17/2020, 8:36 AM
    given a list [a, b, c, d], what is the idiomatic way to split it into two parts at a given index? Using subList feels clunky. I would like to write list.splitAt(2) to get [[a, b], [c, d]
    d
    • 2
    • 4
  • e

    Esa

    08/20/2020, 11:36 AM
    Hi there, I have a couple of extension functions for 
    Iterable<T>
     that has been very useful to me personally, and I wish to make a contribution to the stdlib with those. 🙂 I read through this link and was suggested to make my plans known to #kontributors, however they sent me here. So here's what the functions are basically:
    list.validatedFold
     - this is a function that iterates through the elements of an ordered list, and verifies that elements 
    n
     and 
    n+1
     pass some validation function. returns true if all elements pass, or false on the first element that does not pass (early return).
    list.flatMapIndexedNotNull
     - essentially what the name says, it was relevant for me in one case and I didn't find it in the stdlib.
    Do you think these are appropriate contributions?
    m
    i
    • 3
    • 3
  • d

    Daniele B

    09/03/2020, 11:00 AM
    fun main() {
        val number = 0.001 * 0.001
        println(number.toString())
        // prints 1.0E-6
    }
    How can I make it print “0.00001” ?
    e
    • 2
    • 3
  • d

    diego-gomez-olvera

    09/15/2020, 10:40 AM
    hello! I wonder why
    Reader
    extensions do not use
    @JvmThrows
    https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/jvm/src/kotlin/io/ReadWrite.kt#L120
    i
    • 2
    • 2
  • e

    elect

    09/24/2020, 8:53 AM
    String.getOrNul(index: Int): Char
    where
    nul
    is
    \u0000
    e
    g
    +3
    • 6
    • 23
  • d

    Daniele B

    10/07/2020, 6:32 PM
    how to get the current unixtime in standard library?
    a
    l
    • 3
    • 9
  • r

    rnett

    10/15/2020, 3:40 AM
    This may be more appropriate for #compiler, but I've noticed there's some quite nice utilities in
    org.jetbrains.kotlin.utils.addToStdlib
    in the compiler artifact. Are these things that will be added to the stdlib soon? Because several (especially
    cast
    and
    safeAs
    , for me) are quire nice
    m
    d
    i
    • 4
    • 3
  • s

    spand

    10/22/2020, 6:54 AM
    Is there a common stdlib function I am missing for converting a codepoint to a String ?
    g
    • 2
    • 1
  • s

    spand

    10/23/2020, 11:28 AM
    Is either the implementation or the documentation wrong for
    Map<K, V>.getOrElse
    ? on ie.
    mapOf("1" to null).getOrElse("1") { error("missing") }
    Will throw an error yet
    containsKey("1")
    return
    true
    . The docs says: ... or the result of the [defaultValue] function if there was no entry for the given key. There is an internal
    getOrElseNullable
    that would fix it but I assume it was not chosen for a reason
    ➕ 3
    • 1
    • 1
  • m

    Mark

    10/26/2020, 6:38 AM
    I have a list of
    () -> Item
    lambdas and I want to map it like
    map { it() }
    . Is it possible to write this using a function reference? I was guessing something like
    map((()->Item)::invoke)
    a
    s
    e
    • 4
    • 6
  • m

    mbonnin

    10/30/2020, 2:12 PM
    Reposting here as I just found out about this channel https://kotlinlang.slack.com/archives/C0922A726/p1604066165235100
    d
    • 2
    • 8
  • m

    MiSikora

    11/01/2020, 1:53 PM
    Would it be possible to have a non inline equivalent of enumValues()? Something along the lines of
    public fun <T : Enum<T>> enumValues(enumClass: KClass<T>): Array<T>
    m
    • 2
    • 3
Powered by Linen
Title
m

MiSikora

11/01/2020, 1:53 PM
Would it be possible to have a non inline equivalent of enumValues()? Something along the lines of
public fun <T : Enum<T>> enumValues(enumClass: KClass<T>): Array<T>
m

miha-x64

11/01/2020, 1:59 PM
This is possible with java.lang.Class.
m

MiSikora

11/01/2020, 2:00 PM
I need
KClass
Ah, I found a relevant issue https://youtrack.jetbrains.com/issue/KT-14743
View count: 2