https://kotlinlang.org logo
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
  • d

    Dominaezzz

    11/15/2021, 1:09 PM
    Where can one talk about kotlinx.cli?
    b
    • 2
    • 10
  • h

    holgerbrandl

    11/16/2021, 9:17 AM
    Seriously, why replacing a single function with a very long complex construct?😕
    e
    f
    j
    • 4
    • 8
  • m

    Michael

    11/16/2021, 8:42 PM
    Does anyone know what the new https://dl.bintray.com/kotlin-dev is? I am trying to get kotlinx.atomicfu (https://github.com/Kotlin/kotlinx.atomicfu/commit/1c9f04c3d584e2e6d8ceab133abb8b19d3c0ff51) Because the current version doesn't seem to work with kotlin 1.6
    r
    • 2
    • 2
  • a

    Ansh Tyagi

    11/17/2021, 9:24 PM
    Hey Everyone!, is there any
    MultiMap
    in Kotlin? I wanted to reproduce the following guava data structure into native data structure
    MultimapBuilder.treeKeys().arrayListValues().build<Int, Move>()
    j
    p
    m
    • 4
    • 4
  • o

    okarm

    11/18/2021, 12:00 AM
    Perusing the Jetpack Compose source code, one stumbles upon specialized collection functions such as
    List.fastForEach
    https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/snapshots/ListUtils.kt;l=27
    /**
     * Iterates through a [List] using the index and calls [action] for each item.
     * This does not allocate an iterator like [Iterable.forEach].
     */
    @OptIn(ExperimentalContracts::class)
    internal inline fun <T> List<T>.fastForEach(action: (T) -> Unit) {
        contract { callsInPlace(action) }
        for (index in indices) {
            val item = get(index)
            action(item)
        }
    }
    Is this something that the standard library might be interested in? Yes/no and why?
    j
    e
    +2
    • 5
    • 11
  • h

    holgerbrandl

    11/18/2021, 7:31 PM
    Is there a clip/clamp for numbers in the stdlib (similar to https://stackoverflow.com/questions/4092528/how-to-clamp-an-integer-to-some-range)?
    a
    • 2
    • 2
  • d

    Danish Ansari

    11/21/2021, 8:03 AM
    Can someone please explain diff between
    kotlin.math.max()
    and
    kotlin.comparisons.maxOf()
    ? Both of them seem to be doing the same thing. 2 things I noticed that the later one can compare 3 values also and we can also pass our own comparator. Any other difference than these?
    r
    e
    z
    • 4
    • 4
  • s

    spand

    11/23/2021, 9:11 AM
    I tried searching here and youtrack with no results but has a
    flatten()
    with a
    transform
    been considered ? Seems like an obvious addition which would enable us to skip a list allocation (we have a bunch of
    flatten().map { it.idOfEntity }
    ) not to mention it being a bit simpler:
    flatten { it.idOfEntity }
    A difference with normal
    flatten
    would be that it no longer calls
    addAll()
    which allows it to possibly skip a few grows but given that it can skip an entire copy on the next
    map
    in our case it seems like it should win out. Maybe that would be a reason for keeping both as overloads and not add transform with default parameter. Example implementation:
    public inline fun <T, R> Iterable<Iterable<T>>.flatten(transform: (T) -> R): List<R> {
        val result = ArrayList<R>()
        for (elementIterable in this) {
            for (element in elementIterable) {
                result.add(transform(element))
            }
        }
        return result
    }
    e
    • 2
    • 7
  • r

    rrva

    11/24/2021, 7:33 AM
    If I am doing an awful lot of of
    Map<String, T> + Map<String, T>
    as well as
    Map<String, T>.distinct()
    and this is showing up during profiling as a hotspot, is there some obvious optimization I can do that lets me keep calls to
    plus
    and
    distinct
    but makes it go faster? All involved classes are kotlin data classes so implement that hashCode
    r
    j
    c
    • 4
    • 7
  • d

    Danish Ansari

    12/02/2021, 2:52 PM
    Today in an interview I was asked about scoped functions in Kotlin. I explained all of them very briefly and also explained the difference between each of them very clearly. But I got a counter question "What's the reason scope functions exists? I mean if we can do all of the things/ operation on an object without scope functions, then why use scope functions?" I told "It reduces boiler plate codes" Interviewer: "Any other reason apart from reducing boilerplate code". Now this is the part where I got confused and went speechless. And started wondering about the question. I always s*ck at "WHY" part of the questions in an interview 😅
    r
    p
    +3
    • 6
    • 14
  • d

    dimsuz

    12/09/2021, 12:00 PM
    Most probably wrong channel (point me to the right one). I wonder why does this give me an "overload ambiguity" error?
    fun <R> task(body: () -> R): R = TODO()
    fun <P1, R> task(body: (P1) -> R): R = TODO()
    
    fun main() {
      // overload ambiguity
      task {
        33
      }
    }
    But no ambiguity for these two:
    fun <P1, R> task(body: (P1) -> R): R = TODO()
    fun <P1, P2, R> task(body: (P1, P2) -> R): R = TODO()
    
    fun main() {
      task { v: Int -> 33 }
    }
    f
    • 2
    • 9
  • g

    Greg Rynkowski

    12/13/2021, 5:17 PM
    Is that possible to add a new operator (not overload an existing but add a new one)?
    🇳🇴 2
    j
    b
    +5
    • 8
    • 13
  • o

    Orhan Tozan

    12/17/2021, 3:34 PM
    Updated to Kotlin 1.6.10, but now I'm getting this build error. How do I solve this?:
    java.lang.IllegalStateException: Symbol for kotlin.collections/mutableMapOf|-4813910536206556932[0] is unbound
    	at org.jetbrains.kotlin.ir.symbols.impl.IrBindablePublicSymbolBase.getOwner(IrPublicSymbolBase.kt:52)
    e
    • 2
    • 2
  • e

    Exerosis

    12/18/2021, 9:55 PM
    Why does checking if a nullable element is in a non nullable container not contract that the element be not null if true?
    d
    e
    j
    • 4
    • 6
  • m

    Mustafa Ozhan

    12/21/2021, 5:28 PM
    Hello 👋 Today i wanted to replace my custom
    Result
    class with Kotlin Result then I just realised that my coverage was decreased . Unfortunately none of the
    onSuccess
    and
    onFailure
    methods were covered. • Is there any plan of covering them ? • How do you guys cover these methods are you writing Unit test on Kotlin Result methods ?
    b
    k
    • 3
    • 8
  • s

    SecretX

    12/22/2021, 8:41 PM
    Why does Kotlin compiler let's this trap compile? I introduced an error in production today on my company because of this, I thought the compiler or the IDE would catch something like this, but apparently not.
    ConcurrentHashMap<Int, String>().getOrPut(1) { null } // compiles just fine, but it'll throw in runtime
    mutableMapOf<Int, String>().getOrPut(1) { null } // compiler error: Null can not be a value of a non-null type String
    b
    p
    r
    • 4
    • 7
  • a

    Astronaut4449

    12/27/2021, 4:39 PM
    Just out of curiosity: Was it ever considered to remove the infix function
    to
    from the stdlib and make it some encapsulated function of a map builder scope so that we can write:
    val squared = mapOf { // this refers to some MapBuilderScope<K,V> with builder inference
        1 to 1 // `to` is only visible in the `MapBuilderScope`
        2 to 4
        3 to 9
    }
    m
    r
    j
    • 4
    • 7
  • s

    smallufo

    12/28/2021, 5:57 PM
    Does buildMap changes implementations in 1.6? I asked at kotlin lang forum but it seems that forum is inactive … The following code works well before 1.6
    fun getMap(): Map<String, String> {
        return buildMap {
          if (A) {
            put(key, "A")
          } else {
            put(key, "B")
          }
        }
      }
    but after upgrade to kotlin 1.6 , compiler complains type mismatch :
    Type mismatch.
    Required:
    Unit
    Found:
    String
    Type mismatch.
    Required:
    Unit
    Found:
    TypeVariable(V)?
    Type mismatch.
    Required:
    Unit
    Found:
    String?
    I have to change to this style :
    return buildMap {
          put(key, if (A) "A" else "B")
        }
    It is OK but not so readable. But why !?
    a
    i
    • 3
    • 3
  • r

    Ruckus

    12/30/2021, 5:40 AM
    Would it make sense to add
    typealias Null = Nothing?
    to the stdlib (and preamble)? Common use case:
    class Info<T>(val description: String, val payload: T, ...)
    
    interface Base<T> {
        fun getInfo(): List<Info<T>>
    }
    
    class Derived: Base<Null> {
        override fun getInfo() = listOf(Info("...", null, ...), ...)
    }
    IMO it reads easier than
    class Derived: Base<Nothing?>
    . (Yes, I understand I could use
    Unit
    in this case to achieve basically the same thing in this contrived example. That's beside the point.)
    i
    • 2
    • 5
  • h

    holgerbrandl

    01/02/2022, 1:36 PM
    To transition to the stable Duration API introduced in v1.6, how can I convert a
    kotlin.time.Duration
    to a
    java.time.temporal.TemporalAmont
    ? E.g. to do
    Instant.now() + 5.seconds
    . With the JDK Duration its easy, because it implements
    TemporalAmont
    .
    i
    • 2
    • 2
  • x

    xxfast

    01/03/2022, 11:05 PM
    Are there any way/proposal around string styling syntax, so that
    we can <u>underline</u>,<b>bold</b> or <i>hyphenate</i>
    in
    commonMain
    ?
    n
    • 2
    • 1
  • a

    Ayfri

    01/05/2022, 1:11 PM
    In almost all my projects I add these two methods, could it be a good idea to add them ?
    fun String.remove(pattern: String) = replace(Regex(pattern), "")
    fun String.remove(regex: Regex) = replace(regex, "")
    Or at least the latter one ? I also have in multiple projects this extension
    fun String.get(regex: Regex) = replace(regex, "$1")
    That could be useful to add
    j
    e
    +2
    • 5
    • 7
  • h

    holgerbrandl

    01/09/2022, 7:40 PM
    Why is there no
    Number.minOrNull()
    ?
    d
    e
    n
    • 4
    • 39
  • a

    Ayfri

    01/11/2022, 6:43 PM
    Why does the
    .max()
    and
    .min()
    methods have been removed ?
    b
    e
    • 3
    • 5
  • s

    spand

    01/12/2022, 4:28 PM
    Is there a map merge function ala
    fun <K, V> Iterable<Map<K, V>>.merge(): Map<K, V>
    that I am missing ?
    j
    e
    • 3
    • 4
  • f

    Fleshgrinder

    01/14/2022, 3:02 PM
    Was it already considered by JetBrains to publish dedicated artifacts for all (major) Java versions with Gradle metadata so that Gradle can automatically select the correct one for the Java that is used by a consumer? Today we still have stdlib compiled for Java 1.6 even if we use it in Java 17 and we have to add
    -jdk7
    and
    -jdk8
    to the dependencies (some build tools can do this automatically). Considering that there are a few nice features like
    indy
    that could be enabled also for the stdlib if it were to be compiled for newer versions. Or could this create issues for transitive dependencies that were compiled against a different Kotlin dependency where they expect it to be Java 1.6 ABI?
    👍 1
    e
    i
    • 3
    • 9
  • c

    Chris Fillmore

    01/20/2022, 3:35 AM
    Is there any reason to adopt
    kotlin.Result
    if I’m already using a custom Result type? This is my reasoning: Pros of adopting `kotlin.Result`: • De-duplication • Don’t need to maintain my own type • A portion of my code is essentially an SDK and it would be nice for its clients not to have to use my custom type, and could instead depend on Kotlin’s • Better performance than my current type, since mine is not a
    value
    class (though it’s probably negligible in my use case) Cons: • My custom type is tailored somewhat, providing additional error detail data for e.g. analytics, so I would need to create a custom Exception to carry this information • My custom Failure type doesn’t require an exception, and so can be used for other logical failures without an exception • More development on
    kotlin.Result
    seems to be a no-go? (Per the KEEP https://github.com/Kotlin/KEEP/blob/master/proposals/stdlib/result.md#integration-into-the-language) Anything I may not be considering? Also, any more detail on this:
    We are working in other directions of making signalling error handling more pleasant to use in Kotlin.
    d
    g
    +2
    • 5
    • 10
  • g

    Greg Rynkowski

    01/26/2022, 10:07 AM
    Question about generics. Having this code:
    // all T - java classes implementing ViewDataBinding, each providing a static `bind` method
    // ViewDataBinding - a Java abstract class (with no declaration of `bind`)
    
    interface BindingAware<T : ViewDataBinding> {
        var f: T
    
        fun bind(v: View) {
            // f = T.bind(a)  // <= how to call static method provided by class behind T?
        }
    }
    How to call static method of T, having only T?
    r
    • 2
    • 3
  • f

    Forrest Pangborn

    01/29/2022, 3:54 PM
    I believe in the past I read somewhere in official documentation that the use of
    expect
    +
    actual
    within non-multiplatform modules (or even with a single sourceset) was intentionally supported behavior, but I can't seem to find that anywhere now. does anyone know if this is still the case? everywhere I can find it on the kotlin site, it only seems to reference/encourage use of this mechanism in cases of
    expect
    in a common module and
    actual
    in platform modules. i'm looking to use it with a single common sourceset and wondering if this is something i ought to actually avoid, in case it may become unsupported.
    i
    • 2
    • 4
  • r

    Rob Elliot

    01/30/2022, 3:00 PM
    Candidate mirror function to
    fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>>
    to include in the stdlib:
    fun <T> Iterable<IndexedValue<T>>.withoutIndex(): List<T> = map(IndexedValue<T>::value)
    e
    d
    m
    • 4
    • 5
Powered by Linen
Title
r

Rob Elliot

01/30/2022, 3:00 PM
Candidate mirror function to
fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>>
to include in the stdlib:
fun <T> Iterable<IndexedValue<T>>.withoutIndex(): List<T> = map(IndexedValue<T>::value)
e

ephemient

01/30/2022, 6:27 PM
withIndex provides a indexed view, not a copy, while map copies eagerly
r

Rob Elliot

01/30/2022, 6:53 PM
I'm sure there's a better implementation, it's the concept I'm suggesting. Perhaps I should just have gone with the signature:
fun <T> Iterable<IndexedValue<T>>.withoutIndex(): Iterable<T>
d

Dominaezzz

01/30/2022, 8:03 PM
Feels a bit specific. Like what if the indexes are wrong.
r

Rob Elliot

01/30/2022, 8:11 PM
What if they are? It's just to discard them. Iteration order would be unchanged.
m

marcinmoskala

02/02/2022, 9:53 PM
fun <T> Iterable<IndexedValue<T>>.withoutIndex(): Iterable<T> = UnindexedIterable(this)

internal class UnindexedIterable<T>(private val iterable: Iterable<IndexedValue<T>>) : Iterable<T> {
    override fun iterator(): Iterator<T> = UnindexedIterator(iterable.iterator())
}

internal class UnindexedIterator<out T>(private val iterator: Iterator<IndexedValue<T>>) : Iterator<T> {
    override fun hasNext(): Boolean = iterator.hasNext()
    override fun next(): T = iterator.next().value
}
View count: 2