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
  • l

    louiscad

    04/15/2021, 8:35 PM
    stdlib additions and deprecations in 1.5 are very good! 👍
    w
    • 2
    • 7
  • e

    edrd

    04/16/2021, 3:37 PM
    Would be nice if extension functions for
    Sequence
    were annotated with
    @Terminal
    or something like that to allow easier creation of automated checks for expressions that don't do anything because the developer forgot to call a terminal operation. Me and my team just spent ~2 hours trying to figure out why our code wasn't working after replacing a
    forEach
    call with
    map
    . A detekt rule / IntelliJ inspection would help a lot in this case.
    👍🏻 1
    👍 2
    a
    j
    +2
    • 5
    • 6
  • t

    Tomasz Krakowiak

    04/19/2021, 3:19 PM
    message has been deleted
    e
    • 2
    • 2
  • m

    mbonnin

    04/19/2021, 9:00 PM
    What could go wrong if I'm using
    kotlin-stdlib:1.4.32
    and
    kotlin-reflect:1.3.72
    ? The compiler tells me strange errors could happen but that doesn't sound very specific. Should I care?
    i
    a
    • 3
    • 8
  • b

    bod

    04/23/2021, 2:14 PM
    Hello, World! Any official word on if
    Result
    will be allowed to be returned soon? It's a nice API that we'd like to use, but (unless I'm missing something) currently useless because of this limitation. Just wondering if it's expected to be the case for the foreseeable future.
    i
    • 2
    • 4
  • p

    PHondogo

    04/27/2021, 5:20 PM
    Hello! Why there are no pow functions for Long an Int?
    e
    • 2
    • 2
  • d

    dimsuz

    04/28/2021, 2:16 PM
    I suspect this question was asked multiple times, but it gets me every time and I can't google right away: Having a
    MutableMap<T, MutableList<R>>
    is there a one liner to put an
    R
    into the existing list OR create a list with a single
    R
    , something like
    // when map is {}
    map.magicOp("one", 3) // → { one: [3] }
    map.magicOp("one", 4) // → { one: [3,4] }
    w
    s
    +2
    • 5
    • 17
  • r

    Rob Elliot

    05/05/2021, 6:18 PM
    Would there be any appetite for adding this, as an optimisation to avoid the allocation of a new ArrayList in the current
    Iterable<T>.map
    method?
    public inline fun <T, R> Collection<T>.map(transform: (T) -> R): List<R> {
      return if (this.isEmpty()) emptyList() else (this as Iterable<T>).map(transform)
    }
    👍 2
    👎 1
    s
    • 2
    • 3
  • c

    christophsturm

    05/11/2021, 3:07 PM
    are there plans to merge kotlinx.collections.immutable into the kotlin stdlib or is it just an experiment?
    🇳🇴 1
    e
    s
    +3
    • 6
    • 11
  • l

    Lars Vielhauer

    05/16/2021, 4:50 PM
    Hi all, I wanted to provide some new samples for the stdlib docs but I was a bit surprised about the hashMapOf example.
    val map = hashMapOf<Int, Any?>()
    println("map.isEmpty() is ${map.isEmpty()}") // true
    
    map[1] = "x"
    map[2] = 1.05
    // Now map contains something:
    println(map) // {1=x, 2=1.05}
    From my understanding the last assert is not general enough as the order of elements is not guaranteed, right? This could maybe be changed to two asserts checking for the two elements separately
    e
    d
    • 3
    • 4
  • p

    poohbar

    05/17/2021, 3:00 PM
    what to use instead of the deprecated
    String.capitalize()
    function?
    j
    e
    +5
    • 8
    • 11
  • j

    Javier

    05/17/2021, 9:17 PM
    Unresolved reference: JvmName
    , is it necessary the reflect library now? It is a KMP project with Kotlin 1.5.0
    • 1
    • 1
  • g

    gsala

    05/20/2021, 8:22 AM
    Hey. I'm seeing a strange behavior where even though a
    Result
    is wrapping a failure, the
    isSuccess
    checks return
    true
    . The behavior matches the debugger output there. What could be going on?
    w
    • 2
    • 4
  • m

    mbonnin

    05/22/2021, 12:42 PM
    It looks like compiling
    apiLevel=1.3
    prevents using
    ExperimentalStdlibApi
    ? Is there a way to still allow that? I'd like to use
    String.capitalize(locale: Locale)
    which is stable in 1.4 while still making sure I don't use anything that's only 1.4
    j
    f
    • 3
    • 16
  • b

    Brendan Campbell-hartzell

    06/03/2021, 7:06 PM
    This may be getting into the multiple receivers feature, but I'm wondering if there's a way to do this without having to wrap the IComponent in a with() call or something similar.
    r
    • 2
    • 3
  • t

    thana

    06/07/2021, 8:16 AM
    are there any reasons why the documentation of
    Sequence#take(…)
    does contain code examples only for the
    Iterable#take(…)
    method and even mentions variants of
    take
    that do not even exist on
    Sequence
    ? https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/take.html
    z
    e
    • 3
    • 4
  • c

    christophsturm

    06/10/2021, 11:54 AM
    is there something like `public fun String.substringAfter(delimiter: String, missingDelimiterValue: String = this)`` that instead returns null if the delimeter is not found?
    s
    e
    • 3
    • 27
  • u

    uli

    06/10/2021, 1:13 PM
    I am missing 
    UByte.toString(radix)
     . Was that forgotten? Or is it missing intentionally? (Kotlin 1.5.10)
    h
    i
    • 3
    • 12
  • m

    mboudraa

    06/11/2021, 6:20 PM
    Hey folks. Just noticed this issue https://youtrack.jetbrains.com/issue/KT-44867 where
    Result.getOrThrow
    throw a ClassCastException even if the result is successful. Is there any workaround while the fix is being released. My app depends on it to work properly
    👀 1
    e
    i
    c
    • 4
    • 8
  • d

    Dominaezzz

    06/17/2021, 9:48 AM
    Some sort of no-op comparator would be nice for starting a comparator chain.
    compareBy
    requires to much type info up front, at least the overload that takes a selector.
    i
    e
    • 3
    • 9
  • b

    bod

    06/26/2021, 9:22 AM
    Hello, World! Am I the only one who finds this is kind of missing?
    fun <E> MutableCollection<E>.set(elements: Collection<E>) {
        clear()
        addAll(elements)
    }
    
    fun <E> MutableCollection<E>.set(vararg elements: E) = set(elements.asList())
    d
    e
    a
    • 4
    • 12
  • z

    Zhelenskiy

    06/27/2021, 2:55 PM
    Why is there no flush function in the kotlin.io? I think this is basic enough to be in stdlib.
    i
    • 2
    • 3
  • z

    Zhelenskiy

    06/27/2021, 3:05 PM
    I'm also a bit surprised that there is .random function, but there is no way to give optional distribution to the function to do some kind of softmax that is imho very useful (at least in ML).
    i
    • 2
    • 4
  • l

    louiscad

    07/01/2021, 9:33 PM
    An extension or member to offset an
    IntRange
    would be super useful. One use case is doing text/string replacement (without or with regexes). Such code:
    val offset = -matchResult.range.first
    val rangeToReplaceInMatch = (urlGroup.range.first + offset)..(urlGroup.range.last + offset)
    could become that one liner:
    val rangeToReplaceInMatch = urlGroup.range.offset(-matchResult.range.first)
    BTW, I'm doing that in a Kotlin script, where, in a way, adding extra extensions is mostly adding noise to the signal, as scripts are better short for quick understanding.
    👍 3
    e
    j
    +2
    • 5
    • 26
  • m

    marcinmoskala

    07/08/2021, 11:06 AM
    I would find such a function really useful in stdlib:
    inline fun <reified T : Enum<T>> enumValueOfOrNull(value: String): T? =
        enumValues<T>().find { it.toString() == value }
    // or
    inline fun <reified T : Enum<T>> enumValueOfOrNull(value: String): T? = try {
        enumValueOf<T>(value)
    } catch (e: IllegalArgumentException) {
        null
    }
    👍 4
    👍🏻 1
    r
    • 2
    • 1
  • c

    christophsturm

    07/09/2021, 12:02 PM
    what is the difference between ConcurrentMap getOrPut and computeIfAbsent?
    e
    d
    • 3
    • 5
  • j

    jimn

    08/03/2021, 8:57 PM
    i have not seen this done outside of me doing this, since early days of java, where -ea triggers asserts and asserts make for very cheap production debug logging, e.g. removed. the first one logDebug has been my preferred logging apparatus but i just cribbed ".also" as ".debug" is there any other selective #define mechanism extant or planned for the kotlin language?
    #!kotlin
    
    fun logDebug(debugTxt: () -> String) {
        try {
            assert(false, debugTxt)
        } catch (a: AssertionError) {
            System.err.println(debugTxt())
        }
    }
    
    @ExperimentalContracts
    inline fun <T> T.debug(block: (T) -> Unit): T {
        contract {
            callsInPlace(block, InvocationKind.EXACTLY_ONCE)
        }
       try { assert(false)  } catch (a: AssertionError) {
          block(this)
        }
        return this
    }
    e
    • 2
    • 10
  • c

    christophsturm

    08/05/2021, 7:59 AM
    why does the kotlin result class use Throwable for failure instead of making it generic?
    r
    a
    m
    • 4
    • 8
  • f

    Fleshgrinder

    08/06/2021, 5:18 PM
    Is there a reason why stdlib functions never document the possible exceptions that could be thrown? Maybe a multiplatform thing? I'm looking at https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-reader/read-text.html and have no clue what to expect on JVM. 🤔
    ➕ 9
    e
    i
    • 3
    • 5
  • l

    Luke

    08/30/2021, 6:43 PM
    I was wondering... Why does
    fun String?.orEmpty(): String
    was not defined for
    CharSequence
    ? Is it a multiplatform constraint?
    r
    e
    • 3
    • 5
Powered by Linen
Title
l

Luke

08/30/2021, 6:43 PM
I was wondering... Why does
fun String?.orEmpty(): String
was not defined for
CharSequence
? Is it a multiplatform constraint?
r

Ruckus

08/30/2021, 6:51 PM
I would guess it has to do with expected use. As most APIs (at least from my experience) work with strings, any use of
orEmpty
would then also require a call to
toString
in most any actual use case.
e

ephemient

08/30/2021, 7:02 PM
I wouldn't say that's true - many Android APIs take CharSequence, which can be annotated strings
but it's also pretty easy to write
?: ""
so it's not a huge missing gap
l

Luke

08/30/2021, 7:45 PM
Of course, it's something I could define myself, and absolutely minor in the standard library development. But I would think that the inclusion of
orEmpty
for String alone could justify the equivalent for
CharSequence
, or at least something like
fun <C, R> C?.ifNull(defaultValue: () -> R): R where C : R
, for functional programming style.
r

Ruckus

08/30/2021, 7:48 PM
That could be the case. I haven't done android in many years, so I guess my experience may come with a pretty strong sampling bias...
View count: 4