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
getting-started
  • d

    Draget

    12/12/2020, 5:10 PM
    Different question: I want to return 1 if a map's value is not set or am empty list. Is there a more elegant way than:
    if (!myMap.containsKey(color) || myMap[color]!!.isEmpty()) return 1
    m
    g
    • 3
    • 7
  • d

    Draget

    12/13/2020, 7:41 PM
    Can I deconstruct variables while assigning them? Works:
    var (a ,b) = somethingReturningAPair()
    But what does not work:
    var a: Int
    var b: Int
    (a, b) = somethingReturningAPair()
    Or does it only work when initalizing variables?
    a
    l
    v
    • 4
    • 3
  • c

    Chris Overcash

    12/14/2020, 8:58 PM
    heyo! new to the server, but i've been using Kotlin since alpha koans. i was directed here while doing some research into Desktop Compose.
    👋 3
    s
    • 2
    • 1
  • l

    Lumeidagnacadja

    12/16/2020, 12:19 PM
    Hi as an android developer is it good to know only flutter ?
    r
    j
    • 3
    • 2
  • a

    alex cole

    12/17/2020, 5:49 AM
    Trying to create a list of unique numbers. Why is this statement not working?
    mineLocation = Set<Int>(mineCount) { Random.nextInt(0, length * width)}
    p
    m
    m
    • 4
    • 17
  • k

    keochris

    12/17/2020, 5:31 PM
    I have a fonction that builds a data class out of a JSON response from an API. Until then, that is fine. But when I have pagination, I don’t know how to generate a unique data class from the different pages. Can we “merge” 2 data classes? I’ll probably end up handling a list of Data Classes (which will impact a lot the rest of the code) but if anyone has an elegant idea ... 🙂
    r
    • 2
    • 2
  • d

    Daniele Segato

    12/18/2020, 10:04 AM
    Noob question. I'm using Android Studio (android development) I've Included dependencies:
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2"
    But I cannot use
    async
    and
    launch
    in a
    suspend fun
    suspend fun foo() {
      async {} // Unresolved reference
      launch {} // Unresolved reference
    }
    What am I missing here?! EDIT: nevermind, I was remembering it wronly, I need something like
    coroutineScope {}
    or
    withContext(...)
    or something like that
    m
    w
    +2
    • 5
    • 29
  • r

    Raul Macías

    12/18/2020, 5:51 PM
    👋 ¡Estoy aquí! ¿Qué me he perdido?
    j
    • 2
    • 2
  • b

    ByFloRedstone

    12/19/2020, 1:10 PM
    Hey i made an Annotation Processor in Java now I want to use them also in Kotlin, but the doesnt work. What can I change in the annotationprocessor so that it also works with kotlin?
    t
    • 2
    • 3
  • h

    hazn

    12/20/2020, 4:41 PM
    Hi lovely people! I am interested in developing Kotlin Multiplatform Applications. I have read through the docs and I can't exactly pinpoint what the differences are between Kotlin Multiplattform and Kotlin Multiplatform Mobile
    y
    • 2
    • 2
  • h

    hazn

    12/20/2020, 4:42 PM
    For example, the docs for Kotlin Multiplatform list IntelliJ IDEA as a possible IDE you could use, but the KMM docs only mention Android Studios (for the backend atleast)
    v
    • 2
    • 4
  • p

    poohbar

    12/20/2020, 9:13 PM
    if
    Path
    is now the preferred way over
    File
    in Java, why is there no
    readBytes()
    extension on
    Path
    ?
    r
    n
    • 3
    • 5
  • d

    Daniele Segato

    12/21/2020, 3:10 PM
    I'm trying to use
    MutableStateFlow
    for the first time, but it is not doing what I expect
    private val state = MutableStateFlow<MyState>(INITIAL_STATE)
    
    suspend fun refresh(): MyState {
      val newState = service.refresState()
      this.state.value = newState
      return newState
    }
    
    fun observeState(): Flow<MyState> {
      return state
        .transform { s ->
            if (s !== INITIAL_STATE) {
                emit(s)
            } else {
                refresh() // expecting this to automatically send a new state to the flow
            }
        }
    }
    I was expecing the
    refresh()
    to cause a new state to be emitted, but it didn't. Can someone guide me in the right direction? thanks.
    j
    • 2
    • 4
  • i

    ink

    12/21/2020, 7:44 PM
    Using coroutines what is the proper way to launch/execute multiple independent blocks in parallel? for example
    for taks in tasks:
    launch { task }
    or would it be something like:
    launch { task1, task2, ..., taskN }
    ✅ 1
    d
    a
    • 3
    • 7
  • a

    Animesh Sahu

    12/22/2020, 10:07 AM
    Can somebody spot what's the problem I'm always getting null using this regex:
    val output = (...)
     
     """public \w*\s*class (.+)\.(\w+) \{\n([^\}]*)\}$""".toRegex().find(output)
    Here's the thing to match against:
    Compiled from "Test.kt"
    public final class com.github.animeshz.keyboard.jni.Test {
      public final native void test(kotlinx.coroutines.flow.Flow<java.lang.Integer>);
      public com.github.animeshz.keyboard.jni.Test();
    }
    Seems that regex is correct according to this https://regex101.com/r/PEv4BL/2
    🐛 1
    👍 1
    v
    n
    • 3
    • 21
  • n

    Nat Strangerweather

    12/23/2020, 9:26 AM
    Hi, I need to use this format
    32 + 64 + 4 + 128
    . The problem is that I don't want the numbers to be added up. If I use quotation marks to turn it into a String, I get an error because the method needs Ints. Any ideas?
    ⁉️ 3
    v
    d
    • 3
    • 33
  • d

    Daniele Segato

    12/23/2020, 12:16 PM
    How do I make
    Flow.transformLatest()
    complete when upstream completes?
    upstream
      .transformLatest { state ->
        emitAll(dataForState(state))
      }
    say upstream is
    currentState
      .takeWhile { state -> isCloseNowState(state) }
    This would be easy if I had control of it, I could use
    transformWhile
    , what if I don't? How do I cancel
    dataForState
    when upstream completes? Actually, this is challenging even when I use
    transformWhile()
    cause it is not cancelling the previous one I'd need a
    transformLatestWhile
    d
    • 2
    • 11
  • v

    Victor Cardona

    12/23/2020, 3:14 PM
    I’m having a small issue that is confounding me. I’m trying to gather my validation messages inside a class’ companion object like so:
    internal companion object {
            internal val validation = object {
                val name_blank: String = "Presenter must have a name"
            }
        }
    The problem I’m having is that the name_blank property is not visible anywhere.
    Presenter.validation.name_blank // Error, name_blank not resolved
    m
    • 2
    • 2
  • z

    zsperske

    12/23/2020, 6:19 PM
    if you have a static java method like:
    public static <T> MyFactory<T> of(Class<T> baseType) { ... }
    and you wanted to write a kotlin extension method like:
    fun <T> MyFactory<T>.withSubTypes(types: List<Class<T>) {
       var factory = this
       types.forEach { factory = factory.withSubType(it) }
       return factory
    }
    How do you properly type the static method? If you write something like:
    val factory = MyFactory.of(MyClass::class.java)
                  .withSubTypes(listOf(...))
    You'll get a syntax error on your list:
    Type mismatch. Required: Nothing Found: MyClass
    . Adding explicit type arguments doesn't help.
    v
    • 2
    • 4
  • d

    dan

    12/27/2020, 1:41 AM
    I have a small problem to solve. I need a data structure similar to map but it only allows to assign value the first time. I understood that I could create a customise Map class but I am looking for a shorter way from built int library. Ex:
    m = mutableMapOf<String, Int>()
    m.put("a", 1)
    m.put("a", 1) // throw exception here
    r
    • 2
    • 3
  • a

    alex cole

    12/27/2020, 2:54 AM
    What is the best way to read from files without going through Java.io.File?
    s
    • 2
    • 3
  • f

    F0X

    12/27/2020, 12:26 PM
    Im just starting out with coroutines, so this may be a weird question. Is it possible and how would I go about implementing a
    MainCoroutineDispatcher
    that simply runs the coroutines on an existing main thread?
    c
    d
    • 3
    • 5
  • d

    Dmitry Lukianov

    12/28/2020, 6:53 PM
    Hi there. 👋 I recently wanted to implement a generic interface with Comparable constraint for all numbers, but found that the Number class does not implement the Comparable interface. Are there any reasons for such behavior? All implementations (Double, Byte and etc) implements the Comparable interface (and can be compared to any of numbers except Char) and in general all numbers can be compared (and also used in basic math operations). Maybe it makes sense to make Char comparable with any number and add default Comparable implementation to Number or exclude Char from Number because it does not support basic numeric operations?
    s
    • 2
    • 4
  • s

    Sudhir Singh Khanger

    12/29/2020, 4:05 AM
    Is the following statement correct?
    In Java, arrays store primitive types whereas collections store boxed types. In Kotlin, both arrays and collections store boxed type whereas one can use classes like
    IntArray
    ,
    ByteArray
    , etc. to store primitive data type without boxing.
    e
    n
    • 3
    • 3
  • s

    Sudhir Singh Khanger

    12/29/2020, 5:35 AM
    One would use
    intArrayOf()
    if one wants to initialize an
    IntArray
    with specific and different values otherwise one can simply use
    IntArray()
    . Is that correct?
    * These two are the same
    
    val arr: IntArray = intArrayOf(0, 0, 0)
    val arr = IntArray(3)
    
    * IntArray with different values
    
    val arr = IntArray(3)
    arr[0] = 1
    arr[0] = 2
    arr[0] = 3
    
    vs
    
    val arr: IntArray = intArrayOf(1, 2, 3)
    e
    • 2
    • 1
  • x

    xetra11

    12/29/2020, 3:36 PM
    Given this enum class:
    enum class Trait(code: String) {
            AMBITIOUS("ambitious"),
            HUNTER_1("hunter_1"),
            WRATHFUL("wrathful"),
            CALLOUS("callous"),
            VIKING("viking"),
            EDUCATION_MARTIAL_3("education_martial_3")
        }
    I want to access the
    code
    property as described in this tutorial: https://www.baeldung.com/kotlin-enum Having this statement
    val code = Trait.EDUCATION_MARTIAL_3.code
                                        ^^^^^
    Where
    code
    Unresolved reference: code
    Was the feature removed from the latest Kotlin version or what happened?
    r
    • 2
    • 3
  • n

    Nat Strangerweather

    12/29/2020, 9:25 PM
    Hi, I am using a View Model to pass some values based on user clicks. It is working great apart from one thing: my initial default Int in the View Model cannot be 0, because if I use 0, the app resets when I first open it and click on a button. For my initial value I need this code:
    val notificationManager: NotificationManager =
            context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
    But I read that using a context in a View Model is the wrong approach. Is there a solution to this?
    d
    i
    f
    • 4
    • 9
  • t

    Tony Blundell

    01/01/2021, 11:01 PM
    Hi, quick question about doubles. In Kotlin,
    0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 < 0.8
    evaluates as true, because the left-hand side is actually 0.79r instead of 0.8. What's the best way of dealing with this? I guess I could convert to a string and back, but that feels a little 'hacky'. Is there a better way?
    z
    e
    +2
    • 5
    • 7
  • d

    Daniele B

    01/02/2021, 8:43 PM
    I have a list of numbers:
    val numbers = listOf(1,0,4,0,10,14,16,0,0,34,46)
    how can I transform it in another list where each number is the maximum so far?
    val numbers = listOf(1,1,4,4,10,14,16,16,16,34,46)
    r
    • 2
    • 30
  • e

    Ellen Spertus

    01/05/2021, 1:00 AM
    I ran the following code in the IntelliJ REPL and was surprised that the output was a single line, not three.
    for (num in listOf(1, 2, 3)) println(num)
    123
    Why isn't each element on its own line?
    n
    v
    • 3
    • 8
Powered by Linen
Title
e

Ellen Spertus

01/05/2021, 1:00 AM
I ran the following code in the IntelliJ REPL and was surprised that the output was a single line, not three.
for (num in listOf(1, 2, 3)) println(num)
123
Why isn't each element on its own line?
n

nanodeath

01/05/2021, 1:02 AM
huh. must be a REPL thing
✔️ 1
v

Vampire

01/05/2021, 1:09 AM
Woah, that's unexpected. Maybe a bug even
And here it is: https://youtrack.jetbrains.com/issue/KT-14979
🥇 2
It's not a REPL think, it's a REPL in IntelliJ thing. The commandline REPL does not behave like that according to OP.
n

nanodeath

01/05/2021, 1:14 AM
that last example is what really baffles me
v

Vampire

01/05/2021, 1:14 AM
Why?
n

nanodeath

01/05/2021, 1:15 AM
that's really just emitting two "\n" chars, isn't it?
v

Vampire

01/05/2021, 1:15 AM
yes
View count: 2