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
announcements
  • m

    Mattia Tommasone

    12/11/2020, 1:50 PM
    is there a way to introduce a delay that can be skipped in a test? I tried using
    runBlocking {
        delay(10000)
    }
    and then testing it with
    runBlockingTest
    , but since it’s in another
    runBlocking
    block the delay is not being skipped and my test is, in fact, hanging for 10 secs. I’d like to test that the delay is indeed executed but without really having to wait for it to expire
    f
    g
    • 3
    • 5
  • a

    Animesh Sahu

    12/11/2020, 3:13 PM
    Is there no literals for
    Short
    ? In other words, we aren't able to make compile time constants for Shorts?
    e
    • 2
    • 3
  • l

    LeoColman

    12/11/2020, 4:49 PM
    Hey guys! I'm facing some issues with the no-arg plugin + lazy initialization:
    @No-Arg
    data class MyClass(val foo: String) {
        val bar by lazy { foo[0] }
    }
    
    // Create Foo through reflection, for example, getting it from a database. It will use the zero-arg constructor
    val myFoo = getFoo()
    
    myFoo.bar -> NullPointerException
    When inspecting the bytecode, the bar$delegate (or something like this) is not initialized in the no-arg constructor, and thus is null in runtime. Do anybody have an idea on how to solve this?
    • 1
    • 4
  • n

    Nir

    12/11/2020, 4:57 PM
    Not sure if there's a better channel for this. I had a program throw an exception into main. I actually figured out what the issue was, but when I run my program in Intellij, I can't find even a half decent stack trace or the name of the exception, it's literally just a mountain of gradle garbage. How do I find my actual stack trace? The exception ends with (124 more) but I can't seem to expand it any further
    v
    • 2
    • 11
  • d

    Daniele Segato

    12/11/2020, 5:14 PM
    I've just stumbled into a binary incompatibility issue.
    java.lang.NoSuchMethodError: No direct method <init>(Lkotlin/coroutines/CoroutineContext;I)V in class Lkotlinx/coroutines/flow/internal/ChannelFlow; or its super classes (declaration of 'kotlinx.coroutines.flow.internal.ChannelFlow' appears in /data/app/~~ccBt4dlqHFv3AkedliSnSw==/redacted.package.name.debug-QqdNYvkOKVfFKcKUHZwhVg==/base.apk!classes18.dex)
            at kotlinx.coroutines.reactive.PublisherAsFlow.<init>(ReactiveFlow.kt:51)
            at kotlinx.coroutines.reactive.PublisherAsFlow.<init>(ReactiveFlow.kt:50)
            at kotlinx.coroutines.reactive.ReactiveFlowKt.asFlow(ReactiveFlow.kt:30)
    I had a library compiled with
    org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9
    My project used a more recent version
    org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2
    this apparently caused a binary incompatibility.... It is troubling to me because
    asFlow
    wasn't marked experimental. should I open a ticket / tweet to someone about it? I shouldn't need to release a new version of the library to make it binary compatible with greater versions. WHY this is DEEPLY troubling: If the language doesn't guarantee binary backward compatibility with a previous minor version (1.3.x -> 1.4.x) it means that developers will have to constantly update libraries and eventually maintain multiple versions compiled against multiple version of kotlin for projects that still use a previous minor. THIS IS A NO GO for any language. Libraries compiled for Java 6 run just fine on Java 13. I'm not kotlin need to be that conservative, but at least not break backward compatibility on stable api between minors? Deprecate them for a couple of minors is ok. This is not.
    ⚠️ 1
    m
    a
    g
    • 4
    • 28
  • b

    bbaldino

    12/11/2020, 5:49 PM
    I've got a standalone helper method which does some work and I want to be able to log information within it in the context of the calling methods, but I find it a bit awkward/annoying to have to pass a logger to it, has anyone come up with a good strategy for things like that? I thought about: 1. Define a
    HasLogger
    interface (which defines a
    logger
    property) and make the helper method an extension on that, so that way it could access the logger, but that requires all classes make access to their logger instance public, which seems wrong. 2. Make the helper function an extension function on
    Logger
    directly. This feels like it would be awkward at the call site, as the function itself has nothing to do with logging but would look like
    logger.myHelperFunction(...)
    . Even wrapping the call in a
    with(logger)
    feels a bit weird because it feels like the fact that it logs shoudn't be so explicit. 3. Just suck it up and pass a logger instance. This works but I find it distracting. I have an auto-close-style helper
    withResource
    and calling
    withResource(myResource) { ... }
    feels a lot better than
    withResource(logger, myResource) { ... }
    which seems like it makes it confusing as to which resource is being managed. 4. Have the method use its own logger. This works but our logger instances are part of a hierarchy and include contextual information from the parents, which it would be nice to have when the helper is called in the scope of some class' logger. Has anyone done anything that worked well for a use case like this?
    c
    • 2
    • 1
  • e

    eygraber

    12/11/2020, 8:10 PM
    Is there a stdlib function for something like fold or reduce with a stopping condition?
    var current: Segment? = null
    data
      .segments
      .find { segment ->
        shouldSegmentBeShown()
          .let { (meetsDependency, crossesFrequencyThreshold) ->
            if(meetsDependency && !crossesFrequencyThreshold) {
              current = segment
            }
            meetsDependency && crossesFrequencyThreshold
          }
    }
    n
    • 2
    • 20
  • a

    Animesh Sahu

    12/12/2020, 8:27 AM
    When enabling granular metadata in gradle:
    kotlin.mpp.enableGranularSourceSetsMetadata=true
    kotlin.native.enableDependencyPropagation=false
    I'm getting this, and can't build
    java.lang.IllegalStateException: e: Failed to resolve Kotlin library: D:\Projects\KotlinProjects\keyboard-mouse-kt\keyboard\build\kotlinSourceSetMetadata\commonMain\org.jetbrains.kotlinx-atomicfu-common\org.jetbrains.kotlinx-atomicfu-common-nativeInterop.klib
    It seems the lib is generated and present.
    • 1
    • 1
  • m

    Mikael Alfredsson

    12/12/2020, 10:57 AM
    I know that kotlin accepts the following syntax
    fun <T> f(): Foo where T : Bar, T : Baz { ... }
    but can I do the same with for example a map?
    val map = mapOf<String, T (where T:bar,  T:Baz)>
    a
    • 2
    • 14
  • t

    thana

    12/12/2020, 3:35 PM
    Hi! I was thinking about replacing spring completely with ktor and other tools. As most things seem to be more or less easily replaceable i wasa wondering how to manage transactions in such a case. How do other people address this issue? While there are plenty examples of how to do programmatic transactions with r2dbc or exposed they all are very simplistic and only show how to use it in the data access layer. but of course we actually need to handle it on service layer so the transaction spans over multiple db queries. What tools are there to abstract the transaction handling?
    👀 1
    r
    k
    • 3
    • 6
  • n

    Nir

    12/12/2020, 7:28 PM
    Would be nice if there was some compact way to claim to a when statement that something is exhausive when the compiler cannot see that it is:
    return when(Math.floorMod(value / 90 * rot.dir, 4)) {
            0 -> vector
            1 -> Point(-vector.j, vector.i)
            2 -> Point(-vector.i, -vector.j)
            3 -> Point(vector.j,-vector.i)
            else -> throw Exception("impossible")
        }
    THe compiler here forces me to have the else. And I can't even have an assert False in the else, because that doesn't type check, I have to throw an exception which forces me to make up a name. Maybe something like !else at the end of the when or something like that. Or maybe some kind of special function with a contract that lets you do modulus where the compiler knows that only 0 to N-1 are possible outputs
    r
    a
    +3
    • 6
    • 13
  • n

    Nir

    12/12/2020, 8:16 PM
    Just curious, why is it impossible for overload resolution to distinguish these:
    operator fun<R> R.rem(transform: (R) -> R) = transform(this)
    operator fun<R> R.rem(transform: R.() -> R) = this.transform()
    I'm not even allowed to declare both
    r
    e
    a
    • 4
    • 21
  • n

    nanodeath

    12/13/2020, 5:39 PM
    apologies if this has been brought up before, but there's no Kotlin 1.4.20 (or .21) plugin released for IntelliJ 2020.3. anyone know why? https://plugins.jetbrains.com/plugin/6954-kotlin/versions
    n
    a
    +2
    • 5
    • 9
  • c

    CLOVIS

    12/13/2020, 6:03 PM
    Hi! I have:
    interface Attributes<T>
    enum class StringAttributes : Attributes<T> { ... }
    val attributes: Map<Attributes<Any>, Any>
    val others: Map<StringAttributes, String> = ...
    However, if I write:
    attributes = others
    I get a
    Type Mismatch
    . I guess the solution has something to do with properly using in and out, however I don't understand what the correct way to use those is.
    s
    • 2
    • 2
  • k

    KayCee

    12/14/2020, 4:44 AM
    Hi guys, How can the second sentence produce a NullPointerException?
    lateinit var aLiveData: LiveData<List<..>>
    val list = aLiveData.value
    The crashlytics said there is a NPE in the second line. It occurs occasionally. I dont really get why, I thought it could be about the lateinit so I change it to a nullable variable (despite the fact there is no "lateinit exception"). Is that correct?
    a
    • 2
    • 15
  • p

    Platon Malyugin

    12/14/2020, 5:54 AM
    @KayCee Hi, you don’t define aLiveData
    lateinit var aLiveData: LiveData<List<..>>
    aLiveData = // define live data
    val list = aLiveData.value
    k
    a
    v
    • 4
    • 5
  • a

    Animesh Sahu

    12/14/2020, 8:10 AM
    What's equivalent for kotlin gradle script (build.gradle.kts) of the following configurations in this article/guide. Script is not recognizing
    model { platforms {
    and things like that... Gradle docs seem to have no docs for kts as well in this topic 😞
    v
    • 2
    • 17
  • c

    christophsturm

    12/14/2020, 4:11 PM
    in
    object Blah {
        val context = context()
    }
    how can i get the name of the object (“Blah”) from the context method?
    m
    • 2
    • 2
  • a

    andylamax

    12/15/2020, 5:42 AM
    Hi there, how do I get to make
    10_000_000_000.0.toString()
    to display as
    10000000000.0
    insted of
    1.0E10
    ?
    m
    n
    e
    • 4
    • 11
  • x

    xii

    12/15/2020, 8:05 AM
    hey! is there a way to create an enum class with 'normal' strings?
    a
    o
    • 3
    • 13
  • c

    cafonsomota

    12/15/2020, 11:39 AM
    hello all! I’ve been trying to update my projecto to 1.4.21 (from 1.3.72) and I’m having a couple of errors with kotlin-reflect
    w: Consider providing an explicit dependency on kotlin-reflect 1.4 to prevent strange errors
    w: Some runtime JAR files in the classpath have an incompatible version. Consider removing them from the classpath
    It seems kotlin-reflect is being used by android lint which is causing this error. I’ve already tried to: • declare the right version of kotlin-reflect • resolve it 1.4.21 via
    resolutionStrategy
    But the error persists. Any suggestion on how I can fix it? Thank you 🙂
    c
    j
    • 3
    • 5
  • c

    christophsturm

    12/15/2020, 1:41 PM
    when are kotlin objects intantiated? in
    object MyObj { val blah=getBlah }
    , when is getBlah called? when the containing file is imported? or when a method references
    MyObj.blah
    ?
    m
    r
    a
    • 4
    • 26
  • x

    xii

    12/15/2020, 2:57 PM
    is it possible to throw from inside a map function without having to change the return type of the function to List<Any>?
    a
    c
    +2
    • 5
    • 52
  • n

    Nir

    12/15/2020, 6:42 PM
    How would I suppress the "this declaration is experimental" for unsigned types?
    e
    • 2
    • 9
  • j

    Jeisson Sáchica

    12/15/2020, 7:43 PM
    Should smart casting work normally when using nested
    sealed
    classes? I see a lot of issues like this https://youtrack.jetbrains.com/issue/KT-13495 marked as fixed a long time ago yet I experience this problem in 1.4.21
    r
    j
    • 3
    • 6
  • s

    sbeve

    12/16/2020, 7:55 AM
    How do an object inside a class with a companion object keyword and an object inside the same class with just the object keyword differ? Would the one withour "companion" would be created upon every instance of the class?
    s
    o
    n
    • 4
    • 3
  • z

    zain

    12/16/2020, 10:32 AM
    Is it possible to something similar to be done in Kotlin https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
    g
    c
    v
    • 4
    • 20
  • e

    Edoardo Luppi

    12/16/2020, 11:07 AM
    Let's say I'm developing a chat implementation. A Chat object (one to one communication with polling) create its own internal CoroutineScope with a new thread pool CoroutineContext. This avoid exposing suspend functions, and instead each is wrapped in scope.launch. Is this a good approach?
    a
    • 2
    • 7
  • n

    nfrankel

    12/16/2020, 11:17 AM
    is there a way to do a computation inside a
    when
    block?
    return if (string == null) null
            else {
                val id = Json.parse(string)?.asObject()?.get("id")
                when {
                    id == null -> null
                    id.isString -> Util.entry(id.asString(), string)
                    else -> Util.entry(id.asObject(), string)
                }
            }
    here, i first check a
    if
    then compute the
    id
    then execute my
    when
    using the computed
    id
    it feels not as readable as it could
    a
    m
    • 3
    • 7
  • n

    nfrankel

    12/16/2020, 11:18 AM
    i’d like to put everything in the
    when
    but then, how do i compute the
    id
    so i can use it in the later evaluations?
    v
    k
    s
    • 4
    • 8
Powered by Linen
Title
n

nfrankel

12/16/2020, 11:18 AM
i’d like to put everything in the
when
but then, how do i compute the
id
so i can use it in the later evaluations?
v

Vampire

12/16/2020, 11:38 AM
How about this?
val id = string?.let { Json.parse(it) }?.asObject()?.get("id")
return when {
    id == null -> null
    id.isString -> Util.entry(id.asString(), string)
    else -> Util.entry(id.asObject(), string)
}
k

kenkyee

12/16/2020, 11:45 AM
Could do: when (something) No?
v

Vampire

12/16/2020, 12:24 PM
Not in this case
s

streetsofboston

12/16/2020, 1:46 PM
What about
when(val id =...) {
    ...
}
v

Vampire

12/16/2020, 1:53 PM
I don't think you would win much. This could be used to restrict the scope of
id
, but the
when
result is directly returned, so there is nothing the
id
could leak into. Besides that whyever, then
id
cannot be smart-casted to not-null in the second branch, but you need
return when(val id = string?.let { Json.parse(it) }?.asObject()?.get("id")) {
    id == null -> null
    id!!.isString -> Util.entry(id.asString(), string)
    else -> Util.entry(id.asObject(), string)
}
or
return when(val id = string?.let { Json.parse(it) }?.asObject()?.get("id")) {
    id == null -> null
    id?.isString -> Util.entry(id?.asString(), string)
    else -> Util.entry(id?.asObject(), string)
}
or similar. But I think this is more a compiler bug.
n

nfrankel

12/16/2020, 2:18 PM
thanks for your help folks 🙂
v

Vampire

12/16/2020, 2:19 PM
Nah, it is not a compiler bug and it also cannot work
if you have
when(val ...) { ... }
then the subject is captured as that
val
so that you can use it within the branches easily, but the when expression variant would still be the one with parameter and thus you cannot use arbitrary expressions but only supplying values or ranges that are compared or checking types and as it is not
is String
but
.isString
you need the parameterless variant
View count: 5