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

    spand

    02/12/2020, 8:59 AM
    Are there any generalized functions like joinToString ? Currently I just need something like a forEach but with a sideeffect between elements.
    g
    w
    +3
    • 6
    • 23
  • x

    Xavier F. Gouchet

    02/14/2020, 7:19 AM
    Hi often find myself having a mutableMap where the values are mutable collections, and so I created this extension :
    fun <K, V> MutableMap<K,V>.getOrCreate(key : K, create : ()->V?) : V? {
        return if (containsKey(key) ) {
            get(key)
        } else {
            put(key, create())
        }
    }
    f
    t
    • 3
    • 6
  • f

    Fleshgrinder

    02/14/2020, 2:35 PM
    https://github.com/JetBrains/kotlin/pull/3087 running again and again into situations where I need a
    when
    expression to be exhaustive and it is exhaustive but the compiler cannot know, current example is
    java.nio.ByteOrder
    which has exactly two instances but is not defined as an enum.
    r
    i
    • 3
    • 6
  • l

    Leon K

    02/15/2020, 8:57 PM
    is there something like
    fun <T, K> List<T>.toMapBy(keySelector: (T) -> K): Map<K, T>
    ? i know there is
    .groupBy
    but that returns a map of lists, while most of the time i'd want the equivalent of
    myList.map { it.myKey to it }.toMap()
    d
    • 2
    • 2
  • l

    Leon K

    02/19/2020, 2:47 PM
    small proposal that seemingly does not exist yet:
    /** merge another map into this map,
     * storing the result of applying the given remapping function to the two values if there is a key-conflict. */
    fun <K, V> MutableMap<K, V>.putAllWith(other: Map<K, V>, remappingFn: (V, V) -> V) = other.forEach { (k, v) ->
        merge(k, v, remappingFn)
    }
    any maybe a matching
    plus
    -like operation (
    unionWith
    ?)
    s
    • 2
    • 2
  • e

    elect

    02/21/2020, 12:00 PM
    I find myself usually finding an item by a variable and then return the variable itself, ie: `
    items.list.filter { .. }.maxBy { it.depth }?.depth ?: -1
    what about providing a
    maxOf((E)->T)
    ?
    i
    z
    • 3
    • 7
  • m

    Marc Knaup

    02/26/2020, 5:03 AM
    What about adding the opposite of
    @Suppress
    ? E.g.
    @Enforce
    . For example with non-exhaustive
    when
    expressions:
    ‘when’ expression on sealed classes is recommended to be exhaustive, add ‘is …’ branch or ‘else’ branch instead
    With
    @Suppress("NON_EXHAUSTIVE_WHEN_ON_SEALED_CLASS")
    the warning is gone. With
    @Enforce("NON_EXHAUSTIVE_WHEN_ON_SEALED_CLASS")
    the warning will turn into an error. That would allow catching missing branches earlier (e.g. when adding a new subclass to a sealed class). It would even allow developers to turn any warning into an error for specific code, i.e. depending on the use case. I guess that would be most useful for compiler warnings as the non-exhaustive
    when
    warning is an inspection and wouldn’t cause the compilation process to actually fail 🤔
    s
    s
    g
    • 4
    • 11
  • z

    Zach Klippenstein (he/him) [MOD]

    02/26/2020, 11:58 AM
    Just saw this comment about the experimental time measurement API.
    Clock
    ,
    ClockMark
    , etc are being renamed to
    TimeSource
    ,
    TimeMark
    , etc. https://github.com/Kotlin/KEEP/issues/190#issuecomment-591081265
    👀 2
    ❤️ 1
    m
    • 2
    • 1
  • x

    Xavier F. Gouchet

    03/03/2020, 11:00 AM
    Didn't find it but is there a
    substring
    method :
    fun String.substring(maxLength : Int): String {
        return if (length > maxLength) substring(0, maxLength) else this
    }
    d
    k
    • 3
    • 4
  • a

    arekolek

    03/04/2020, 11:21 AM
    https://blog.jetbrains.com/kotlin/2020/03/kotlin-1-3-70-released/
    You know this convention in Kotlin: having a pair of functions, where the first one throws an exception if the operation isn’t possible, and the second one returns 
    null
    , like 
    string.toInt()
     and 
    string.toIntOrNull()
    . Now we’ve added new 
    randomOrNull()
     and 
    reduceOrNull()
     counterpart functions, following the same convention
    If this is a convention, then why there is no
    max(): T
    and
    maxOrNull(): T?
    and instead we have a
    max(): T?
    ? We had a discussion about it here https://kotlinlang.slack.com/archives/C1H43FDRB/p1551864308014200
    i
    s
    +3
    • 6
    • 19
  • s

    Slackbot

    03/05/2020, 1:22 PM
    This message was deleted.
    m
    s
    +9
    • 12
    • 32
  • j

    jw

    03/13/2020, 3:10 PM
    Is 1.4's
    Result
    binary compatible with 1.3.70's? Or, put another way, how dangerous would it be to ship a library which uses
    Result
    with 1.3.70 in anticipation of it being available for use in 1.4?
    e
    g
    • 3
    • 6
  • l

    LeoColman

    04/03/2020, 3:06 PM
    Hey! I was browsing reddit and saw an article with some fuel for thought. https://www.reddit.com/r/Kotlin/comments/ftnvzd/stop_scan_and_scanreduce_before_its_too_late/
    ⬇️ 1
    c
    i
    s
    • 4
    • 4
  • l

    louiscad

    04/16/2020, 2:31 PM
    Hello, I spotted this very interesting KEEP about
    fun CharSequence.occurencesOf
    . It's shown as "Implemented" (with no version specified), but I'm not finding it in autocomplete in Kotlin 1.3.72. Is that a mistake or is there a way to access it? https://github.com/Kotlin/KEEP/blob/master/proposals/stdlib/occurrences-of.md
    s
    • 2
    • 1
  • m

    miha-x64

    04/17/2020, 8:11 PM
    Shouldn't stdlib contain such a function?
    fun CharSequence.equalsIgnoreCase(that: CharSequence): Boolean {
        val len = length
        if (that.length != len) return false
        return regionMatches(0, that, 0, len, ignoreCase = true)
    }
    Dealing with `CharSequence`s is pretty painful in Java, I'd like Kotlin to fix this…
    d
    j
    • 3
    • 4
  • b

    bod

    04/23/2020, 6:02 PM
    Hello, World! Hey I'm very often finding myself needing a
    indexOf
    but with a default value (instead of -1). Is this something that exists? If not, I'm gonna make my own extension - what would you name it? 🙂
    s
    • 2
    • 2
  • n

    natpryce

    04/24/2020, 11:36 AM
    Question: why is
    emptyList()
    a generic function that returns a
    List<T>
    , instead of a non-generic function that returns a
    List<Nothing>
    ? (Or even a constant or object?)
    d
    i
    z
    • 4
    • 8
  • m

    miha-x64

    04/24/2020, 4:30 PM
    Btw, why Kotlin has its own
    object EmptyList
    ? There are already
    Collections.emptyList()
    and `List.of()`…
    s
    j
    • 3
    • 10
  • m

    miha-x64

    04/25/2020, 4:24 PM
    I love such an idiom in Rust:
    s
    d
    +3
    • 6
    • 15
  • l

    Leon Linhart

    05/02/2020, 10:48 PM
    What about a function
    inline fun <T> __apply(receiver: T, block: T.() -> Unit): T
    (name tbd) which behaves excactly like the current`apply`. Reasoning: When using Java libraries I tend to avoid extension functions with "simple" names (such as
    apply
    ,
    run
    ,
    let
    , etc.) since it is always possible that a method with the same name is added to a class in a Java library. Due to Kotlin's resolution rules this could easily result in a source-incompatible change (depending on the exact method signature). However, with
    __apply(object)
    this would not be a problem. Additionally, there is already a similar pattern in the stdlib:
    with
    and
    run
    . (See also https://kotlinlang.org/docs/reference/scope-functions.html#function-selection) Bonus "real-world example": https://github.com/LWJGL/lwjgl3/issues/554
    d
    • 2
    • 1
  • p

    Pedro González

    05/03/2020, 3:12 AM
    I understand the kotlin "equivalent" of java's try-with-resources is the use() library function However, if exceptions occurs, use will just fail silently. Is there any alternative function/idiom that allows to manage exceptions explicitly without having to manually close the used resource?
    d
    b
    d
    • 4
    • 7
  • g

    gildor

    05/08/2020, 3:51 AM
    I would just use if/else
    ➕ 3
    m
    • 2
    • 11
  • m

    miha-x64

    05/09/2020, 10:20 PM
    public infix fun IntProgression.step(step: Int): IntProgression {
        checkStepIsPositive(step > 0, step)
        return IntProgression.fromClosedRange(first, last, if (this.step > 0) step else -step)
    }
    else
    branch is dead here
    e
    • 2
    • 2
  • b

    bod

    05/12/2020, 9:20 AM
    Hello, World! Is it still a fact that there is no MultiMap in the stdlib?
    g
    r
    +2
    • 5
    • 28
  • a

    asad.awadia

    05/15/2020, 3:46 PM
    is there no equivalent
    s
    z
    n
    • 4
    • 19
  • m

    maxmello

    05/21/2020, 2:03 PM
    Regarding maxBy, I have the following situation: I want to use maxBy for a collection on a value which is nullable, and if the value is null I don’t actually want it but instead return null. The selector of maxBy requires the return value to be not null, so I have to write
    maxBy { it.someNullableValue ?: Long.MIN_VALUE }
    . This will return me the first value if the list is not empty, so I would have to append
    .takeIf{ it?.someNullableValue != null}
    , which is fine for short cases like this, but when the value to compare is not top level but itself created by a more complex expression like
    it.someList.filter{…}.maxBy{…}?.someNullableValue
    you need to write that same complex expression twice in the
    takeIf
    part. So I wrote
    maxByOrNullIfNull
    (kind of a bad name I know)
    inline fun <T, R : Comparable<R>> Iterable<T>.maxByOrNullIfNull(selector: (T) -> R?): T? { // Allows selector to return R?
        val iterator = iterator()
        if (!iterator.hasNext()) return null
        var maxElem: T? = iterator.next()
        var maxValue: R? = selector(maxElem!!) // Here, we know maxElem is not null
        if(maxValue == null) {
            maxElem = null
        }
        if (!iterator.hasNext()) return maxElem
        do {
            val e: T = iterator.next()
            val v: R? = selector(e)
            if(v != null) {
                if(maxValue == null) {
                    // If we don't have any non-null element yet, set the current element / value
                    maxElem = e
                    maxValue = v
                } else if (maxValue < v) {
                    // Here, we know both values are not null, so we do the usual comparison
                    maxElem = e
                    maxValue = v
                }
            }
        } while (iterator.hasNext())
        return maxElem
    }
    I would argue that this would be a nicer default behavior for
    maxBy
    , as it doesn’t really change the behavior for non-null cases, but makes clear that null values will always be considered “less” than any actual value in the comparison (no more need for
    ?: Long.MIN_VALUE
    or something) and that we want an element with an actual value, not one that has no value for the comparison.
    d
    s
    j
    • 4
    • 3
  • d

    Derek Peirce

    05/22/2020, 7:15 PM
    IntRange.forEach
    uses
    Iterable.forEach
    , so
    (1..n).forEach { ... }
    creates an
    Iterator
    , while
    for (k in (1..n)) { ... }
    is optimized to use a while-loop, not even creating the original
    IntRange
    object. Could
    IntRange
    receive its own
    forEach
    extension method to preserve this optimization, and perhaps receive additional optimizations for common methods like
    map
    ?
    r
    i
    • 3
    • 3
  • g

    gsala

    05/27/2020, 7:12 AM
    Is there a better way to write these bit masks?
    val impulseDownAllowed: Boolean = capabilitiesByte and 0x10.toByte() != 0.toByte()
    val bleMovementAllowed: Boolean = capabilitiesByte and 0x20.toByte() != 0.toByte()
    e
    e
    • 3
    • 18
  • b

    Bornyls Deen

    05/27/2020, 8:16 PM
    I've found myself implementing this in a couple of different projects now... do you guys think there might be a place for it in the standard library? The closest I've got using the existing functions is chaining
    filterIsInstance
    and
    first
    but I imagine this is a little better performance wise as we are returning after the first match. It's like
    first
    is to
    filter
    ... `firstIsInstance`/`filterIsInstance` 😄
    inline fun <reified T> Iterable<*>.firstIsInstance(): T? {
        for (element in this) {
            if (element is T) {
                return element
            }
        }
    
        return null
    }
    ➕ 1
    d
    t
    c
    • 4
    • 4
  • a

    asad.awadia

    06/03/2020, 8:44 PM
    what is the most idiomatic way of going through an array of json and setting a field on the object with the max on a particular field - and removing that field from everyone else
    d
    d
    • 3
    • 3
Powered by Linen
Title
a

asad.awadia

06/03/2020, 8:44 PM
what is the most idiomatic way of going through an array of json and setting a field on the object with the max on a particular field - and removing that field from everyone else
d

Dominaezzz

06/03/2020, 8:53 PM
maxBy
and
forEach
a

asad.awadia

06/04/2020, 12:17 AM
is it possible to do it in one pass?
d

Derek Peirce

06/06/2020, 8:16 PM
maxBy
does perform a check on each item, so you could perform the removal within that check.
View count: 3