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

    Slackbot

    03/16/2020, 4:01 PM
    This message was deleted.
    n
    1 reply · 2 participants
  • p

    Pawel

    03/16/2020, 6:19 PM
    Hi! I am having logic similar to posted below. Is there any way to do it better?
    var a: Int? = null
    try {
        a = doSthToGetA()
        useA(a)
    } catch(ex: AnyExc) {
        doSthWithA(a)
    }
    s
    3 replies · 2 participants
  • x

    xii

    03/16/2020, 8:28 PM
    or rather... if another parameter, c, is not null
    r
    1 reply · 2 participants
  • m

    Max

    03/16/2020, 8:29 PM
    Hello everyone does anyone know how to enable simple
    println()
    during a gradle task? (especially a continuous one)
    l
    1 reply · 2 participants
  • m

    Mike Conley

    03/17/2020, 6:09 AM
    depending on what
    foo
    actually does
    a
    c
    120 replies · 3 participants
  • k

    Kashif

    03/17/2020, 6:10 AM
    please do chat in a thread
    :thread-please: 5
    👍 7
    👮‍♂️ 5
    m
    1 reply · 2 participants
  • p

    Prateek

    03/17/2020, 8:24 AM
    Duplicate class kotlin.reflect.KClasses found in modules jetified-kotlin-reflect-1.0.7.jar (org.jetbrains.kotlin:kotlin-reflect:1.0.7) and jetified-kotlin-stdlib-1.3.70.jar (org.jetbrains.kotlin:kotlin-stdlib:1.3.70)
    Can anybody help me figure out this error? I am unable to run tests because of it
    m
    j
    7 replies · 3 participants
  • p

    PandaH.

    03/17/2020, 10:16 AM
    "On the Java platform, numbers are physically stored as JVM primitive types, unless we need a nullable number reference (e.g.
    Int?
    ) or generics are involved. In the latter cases numbers are boxed." What does it mean by boxed?
    m
    m
    3 replies · 3 participants
  • p

    Paul N

    03/17/2020, 12:29 PM
    I've just been handed over a problem from a colleague - he's trying to build a Kotlin project with about 650 classes in it, and the gradle build just sits there on the compile Kotlin phase, with the CPU hitting over 500% on the compile process. I'm stumped as to why this is so slow. The classes are all JPA entities. Does anyone have any pointers as to why this might be ?
    1 reply · 1 participant
  • t

    Tsvetan Ovedenski

    03/17/2020, 1:37 PM
    Hey!
    data class Item (val name: String)
    
    sealed class Permission <T> {
        object Create : Permission<Unit>()
        object Edit : Permission<Item>()
    }
    
    fun <T> verify(permission: Permission<T>, item: T): Boolean = when (permission) {
        is Create -> true
        is Edit   -> item.name == "editable" // Unresolved reference: name
    }
    For some reason I expected that when it's known that
    T
    is
    Item
    (as it is in
    Edit
    ), then
    item
    would be properly casted, but I realise that maybe I expected too much. Any idea on how to connect the two (
    permission
    and
    item
    )?
    f
    c
    +2
    12 replies · 5 participants
  • b

    bod

    03/17/2020, 4:01 PM
    Hello, World! I'm finding myself doing this a lot (especially with enums):
    val isStateXyz = xx.state in setOf(FOO, BAR, FOOBAR)
    Is this idiomatic? Also, I think it may be a bit bad performance... So I was thinking of creating this:
    inline fun Any?.equalsAny(vararg objects: Any?): Boolean = objects.any { this == it }
    and use it like this
    val isStateXyz = xx.equalsAny(FOO, BAR, FOOBAR)
    Is it a good idea or should I just keep using
    in
    ? Thoughts?
    a
    m
    11 replies · 3 participants
  • s

    Steve

    03/17/2020, 4:52 PM
    I have a Repository class that first tries to validate something by going online, but if not available, falls back to an offline validator. I'm using sealed classes to return the state. Right now, return states are all in the same sealed class. I'd like to separate them so only the offline validator can return the offline ones, and only the online one can return online states. But I'd like the Repository to be able to return any of them (whether the validation happens online or offline matters to the upper layers, mainly for displaying to the user). How can I accomplish this?
    t
    r
    9 replies · 3 participants
  • c

    cedric

    03/17/2020, 8:01 PM
    the short story is that it exists for compatibility with code that came before generics were a thing.
    @Mike Conley That's not quite true, erasure was mostly picked for its superiority over reification in many different areas. It would have been possible to have reified generics in Java without breaking any backward compatibility, it just wouldn't have been wise 🙂
    👍 1
    m
    1 reply · 2 participants
  • a

    Anastasia Finogenova

    03/17/2020, 10:06 PM
    Hey, I have a code style question. The code style conventions say "prefer using single expressions". So what can be considered a single expression in Kotlin? I have my understanding but found today that my coworker has a different view and there is no definition in the docs on this as far as I can find. So would like to hear what do you consider a "single expression"
    l
    d
    +1
    10 replies · 4 participants
  • h

    hooliooo

    03/17/2020, 10:39 PM
    Is there a Kotlin/Java library that can handle this https://stackoverflow.com/questions/1109536/an-algorithm-for-inflating-deflating-offsetting-buffering-polygons
    b
    1 reply · 2 participants
  • c

    Christian Sousa

    03/18/2020, 1:00 PM
    Hello all, I’m trying to do something I usually do on JS that follow something like this:
    const myArray = ['1', '2', '3']
    let myObj = {
      default = '0'
    }
    
    myArray.forEach(elem => {
      myObj = {
        ...myObj,
        [`newProperty-${elem}`] = elem
      }
    })
    Is there any way to do something like that in Kotlin? Basically, I just need a way to create an object with a variable amount of properties
    s
    c
    +1
    6 replies · 4 participants
  • c

    Cosmin Victor Celea

    03/18/2020, 2:07 PM
    🛑 Hi does anyone have any good examples of throttling in a REST Api. Extra points if is a http4k based API. 🙏 Server side.
    t
    21 replies · 2 participants
  • l

    LastExceed

    03/18/2020, 2:16 PM
    suspend fun main() {
       val items = MarketAPI.getItems()
    
       for (index in items.indices) {
          println(items[index])
       }
    
       items.forEach {
          println(it)
       }
    }
    the return type of
    MarketAPI.getItems()
    is
    List<Item>
    where
    Item
    is a simple data class storing 3 Strings. the first loop works fine, the second one gives me this error: https://hastebin.com/ewuvakikuy how is this possible? how can the way i iterate through the items affect the serialization AFTER it happens? I cant even figure out where exactly it happens. the stacktrace says line 12 in main.kt, however that file only has 11 lines. I set a breakpoint and stepped through, the crash occurs as soon as i reach the second loop. but due to coroutine shenanigans the stacktrace isnt very helpful
    j
    c
    +1
    54 replies · 4 participants
  • g

    Gilberto Diaz

    03/18/2020, 3:03 PM
    Which one is the channel for language questions?
    l
    1 reply · 2 participants
  • a

    Ajinkya Saswade

    03/18/2020, 3:03 PM
    Just published an article on Jetpack compose. About how it works, why it was introduced, what problems it solves, etc. Please go through it whenever you get time and provide your feedback. Thanks https://medium.com/@ajinkyasaswade09/jetpack-compose-what-problem-does-it-solves-110ed9314dbe
    c
    3 replies · 2 participants
  • a

    Animesh Sahu

    03/18/2020, 3:19 PM
    Can we make something like try.kotlinlang.com ? and host it to a local server, for fast debugging purposes?
    :kotlin-flag: 2
    s
    r
    6 replies · 3 participants
  • c

    Christian Sousa

    03/18/2020, 3:42 PM
    What’s the best way to convert a Map(or MutableMap) into a Data Class?
    l
    r
    +1
    11 replies · 4 participants
  • c

    Chills

    03/19/2020, 8:44 AM
    isnt sealed class take more memory than normal class? considering O(k+m)
    m
    r
    +1
    13 replies · 4 participants
  • i

    ilya_ryabchuk

    03/19/2020, 11:24 AM
    Seems like Kotlin extensions was made before Kotlin itself. 🤔 🤔
    😆 13
    n
    g
    2 replies · 3 participants
  • c

    Christian Sousa

    03/19/2020, 11:39 AM
    Anyone knows why I can’t do something like this?
    fun myFunction(list: List<String>): List<String> {
        return list.map {
            return it
        }
    }
    It complains about the return type being a string instead of a List<String>
    d
    r
    +1
    8 replies · 4 participants
  • c

    Chills

    03/19/2020, 12:39 PM
    question on sealed class can i have sealed class with following possibilty for example have a sealed class name Response with following data class Header,Body and Error often ill have Header and Body or Header and Error or Body or Error alone if for example i declare SealeadClass<H,B> if something gone wrong cant pass SealedClass.Error() as response.
    e
    m
    +2
    42 replies · 5 participants
  • s

    stanislav.erokhin

    03/19/2020, 2:54 PM
    We are starting the 1.4-M1 (the first preview version of the upcoming Kotlin 1.4.0) release activities. Please be patient, it will take a bit of time. It will be officially out only after the blog post appears in blog.jetbrains.com/kotlin. In the next couple of days you may see new artifacts appear in various repositories. Since we don’t have full control of all the systems involved, you may temporarily observe and inconsistent state of the 1.4-M1 world. Please don’t be alarmed, the blog post will notify you when we reach a consistent state 🙂 Looking forward to your feedback on 1.4-M1 when it’s ready. Have a nice Kotlin!
    👍 16
    :kotlin-flag: 19
    o
    m
    2 replies · 3 participants
  • c

    Chills

    03/19/2020, 3:16 PM
    Nothing
    cant be reified type? why
    s
    1 reply · 2 participants
  • e

    elect

    03/19/2020, 4:05 PM
    performance-wise, better a
    () -> Unit
    or a
    Runnable
    (on pure kotlin)?
    s
    c
    8 replies · 3 participants
  • a

    angarron

    03/19/2020, 4:34 PM
    argghhh I have a CME in my app that I can't quite understand -- would greatly appreciate any help! I have this code (simplified a bit):
    @Synchronized
    fun notify(updates: Set<UpdateSource>) {
      Log.d("findme", "notify START: $updates")
      observers.forEach { observer ->
        /* stuff */
      }
      Log.d("findme", "notify END")
    }
    
    @Synchronized
    private fun disconnect(observer: Observer) {
      Log.d("findme", "disconnect START")
      observers.remove(observer)
      Log.d("findme", "disconnect END")
    }
    and I see these logs:
    2020-03-19 09:25:16.545 21962-22072/com.discord.debug D/findme: notify START: [com.discord.stores.StoreUser@c7528b5, com.discord.stores.StoreUser$Companion$UsersUpdate$1@91882e5]
    2020-03-19 09:25:16.548 21962-22072/com.discord.debug D/findme: disconnect START
    2020-03-19 09:25:16.548 21962-22072/com.discord.debug D/findme: disconnect END
    Can anyone explain how it's possible that "notify END" never prints? if that
    forEach
    was hanging, I would expect a hung thread, but we are able to enter the
    disconnect
    method -- which means that I feel like I'm misunderstanding something about
    @Synchronized
    a
    p
    5 replies · 3 participants
Powered by Linen
Title
a

angarron

03/19/2020, 4:34 PM
argghhh I have a CME in my app that I can't quite understand -- would greatly appreciate any help! I have this code (simplified a bit):
@Synchronized
fun notify(updates: Set<UpdateSource>) {
  Log.d("findme", "notify START: $updates")
  observers.forEach { observer ->
    /* stuff */
  }
  Log.d("findme", "notify END")
}

@Synchronized
private fun disconnect(observer: Observer) {
  Log.d("findme", "disconnect START")
  observers.remove(observer)
  Log.d("findme", "disconnect END")
}
and I see these logs:
2020-03-19 09:25:16.545 21962-22072/com.discord.debug D/findme: notify START: [com.discord.stores.StoreUser@c7528b5, com.discord.stores.StoreUser$Companion$UsersUpdate$1@91882e5]
2020-03-19 09:25:16.548 21962-22072/com.discord.debug D/findme: disconnect START
2020-03-19 09:25:16.548 21962-22072/com.discord.debug D/findme: disconnect END
Can anyone explain how it's possible that "notify END" never prints? if that
forEach
was hanging, I would expect a hung thread, but we are able to enter the
disconnect
method -- which means that I feel like I'm misunderstanding something about
@Synchronized
a

araqnid

03/19/2020, 4:42 PM
is notify invoking something that is then invoking disconnect() on the same thread? monitors are re-entrant, i.e. one thread can keep re-entering synchronized methods and it just increases an internal counter and unlocks at the end
that would explain CME (= ConcurrentModificationException, I assume)
for something like an observer list, I’d usually use CopyOnWriteArrayList to avoid it
a

angarron

03/19/2020, 4:45 PM
yup im pretty sure I have something calling disconnect, that makes sense. thanks!
p

pedro

03/19/2020, 4:45 PM
I assume something in the for loop inside
notify
called
disconnect
. You never saw the “END” log because the exception was thrown. The stacktrace would be something like 1. notify 2. disconnect so the notify method had not finished yet
View count: 1