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

    Janez Kolar

    10/15/2020, 12:40 PM
    Hi developers, I would need one advice. I have collection of data ( 1000 instances of Car). I have one thread to change data and multiple threads to access data.. I need to access it by id, so MutableMap is selection. But I need also filter data out by range of lon, lat to calculate the closest few. What would be the fastest and the best approach? Currently I have (code bellow), but this searches through all elements.
    fun nearCar(minLat: Float, maxLat: Float, minLon: Float, maxLon: Float): List<Car> {
        return mutableMapCars.values.parallelStream().filter {
            it.lat > minLat &&
                    it.lat < maxLat &&
                    it.lon > minLon &&
                    it.lon < maxLon
        }.toList()
    }
    data class Car(
        val id : Long,
        val registration : String,
        val lon: Float,
        val lat: Float
    )
    s
    m
    +2
    • 5
    • 6
  • f

    frankelot

    10/15/2020, 2:28 PM
    I feel silly having to ask this but… what’s going on here?
    m
    v
    +2
    • 5
    • 85
  • b

    Big Chungus

    10/15/2020, 4:37 PM
    Does anyone know if
    bin/kotlinc
    found in kotlin-native cli release tar can be used interchangeably with the one found in kotlin-compiler.zip?
    u
    • 2
    • 2
  • a

    aarjav

    10/15/2020, 9:58 PM
    Is there a kotlin common / multi platform logging library or is it just preferred to use platform specific ones?
    m
    • 2
    • 2
  • x

    xii

    10/16/2020, 2:16 AM
    hey! I'm using kotlin with coroutines with spring webflux and I'm having some issues regarding KContinuation when trying to use PreAuthorize
    • 1
    • 8
  • k

    KamilH

    10/16/2020, 8:06 AM
    Is there any Plugin that will let me generate function that creates an instance of
    data class
    with its default values? For example I have:
    data class User(
        val id: String,
        val deviceId: String
    )
    and plugin will generate:
    fun userOf(
        id: String = "",
        deviceId: String = "",
    ): User =
        User(
            userId = userId,
            deviceId = deviceId,
        )
    or something similar? (Sorry if wrong channel)
    m
    r
    • 3
    • 4
  • e

    eenriquelopez

    10/16/2020, 9:36 AM
    Hi folks. I am having a behavior in Kotlin that does not look right for me. So I have declared the following:
    val title: (locale: Locale) -> String? = {
        getPrompt(it.language)
    }
    
    fun getPrompt(string: String) : String? {
        return if (string == "A") null
        else "A"
    }
    getPrompt
    can return null, hence the
    String?
    However, the following check returns a warning from the compiler ("the comparation can be simplified since title is never null")
    if (title == null) {
    
    }
    But title can effectively be null. Is this a bug on AS/JetBrains?
    s
    a
    k
    • 4
    • 7
  • d

    Daniel

    10/16/2020, 10:50 AM
    How can I create a sub-scope of a CoroutineScope? I'm looking for something like
    val parentScope: CoroutineScope
    val childScope = parentScope.something()
    I want childScope to be cancelled if parentScope is, but for parentScope not to be cancelled if childScope is
    m
    • 2
    • 2
  • a

    Animesh Sahu

    10/16/2020, 11:39 AM
    This seems to be an interesting topic, https://stackoverflow.com/q/64385753/11377112 anybody giving it a shot?
    f
    • 2
    • 1
  • c

    ciscorucinski

    10/16/2020, 12:29 PM
    I'm not sure of the best channel for this discussion, but it deals with delegates and how they are used to grab Property File values. I have seen it described very similarly before in an article that we can use a simple convention such as
    val pluginGroup: String by project
    This will search for .property files for the key
    pluginGroup
    and return it's value as a
    String
    . I am impressed by that, but how the heck does this magic work? This will only return
    String
    values, so even if we have the following in the .properties file...
    platformDownloadSources = true
    It will still only return
    "true"
    as a
    String
    . I am curious of how this mechanism works and why it is limited to only
    String
    and why it is limited to the specific name I have for the variable. Meaning I must name my variable the same as is in the .properties file.
    v
    e
    • 3
    • 9
  • s

    streetsofboston

    10/16/2020, 2:47 PM
    I have this piece of code and I’m wondering if this is a bug or just not possible (as designed) for the type inference of Kotlin. Here is a snippet:
    class MyList<T> {
        @JvmName("flatMapList")
        fun <R> flatMapList(block: Function1<T, List<R>>): MyList<R> = TODO()
    
        @JvmName("flatMapListPair")
        fun <R> flatMapList(block: Function1<T, Pair<R, R>>): MyList<R> = TODO()
    
        @JvmName("flatMapList2")
        fun <R> flatMapList2(block: (T) -> List<R>): MyList<R> = TODO()
    
        @JvmName("flatMapListPair2")
        fun <R> flatMapList2(block: (T) -> Pair<R, R>): MyList<R> = TODO()
    }
    
    fun test() {
        val x = { it: Int -> Pair("1", "2") }
        val y = { it: Int -> listOf("1", "2") }
    
        MyList<Int>().flatMapList(x) // OK
        MyList<Int>().flatMapList({ it: Int -> Pair(1, 2) }) // ERROR
    
        MyList<Int>().flatMapList2(x) // OK
        MyList<Int>().flatMapList2({ it: Int -> Pair(1, 2) }) // ERROR
    
        MyList<Int>().flatMapList(y) // OK
        MyList<Int>().flatMapList({ it: Int -> Pair(1, 2) }) // ERROR
    
        MyList<Int>().flatMapList2(y) // OK
        MyList<Int>().flatMapList2({ it: Int -> Pair(1, 2) }) // ERROR
    }
    Why does the compiler (and IDE) generate an error when directly assigning the lambda, but it compiles fine when using a temporary variable (
    x
    and
    y
    )?
    m
    n
    • 3
    • 3
  • d

    Daniel

    10/16/2020, 4:35 PM
    I'm running into a concurrency issue I don't understand how to fix. I have a function in my repository called 
    getTile
    , which may need to call 
    renewAccessToken
    . If I make ten parallel calls to 
    getTile
    , and I need to renew the token, one call should do the renewing, and the rest should block until it is done. I'm wondering if I want something that emits a stream of (mostly-identical) access tokens, which getTile pulls the latest access token from. The stream then chooses whether to renew or present a stale value
    n
    m
    p
    • 4
    • 27
  • k

    kartik1712

    10/17/2020, 10:22 AM
    Hi all!, I am having a bit of trouble setting up Kotlin multiplatform project with multiple gradle modules.
    Could not create an instance of type org.jetbrains.kotlin.gradle.targets.js.subtargets.KotlinBrowserJs.
    Failed to apply plugin [class 'org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootPlugin']   > The Kotlin Gradle plugin was loaded multiple times in different subprojects, which is not supported and may break the build.
         This might happen in subprojects that apply the Kotlin plugins with the Gradle 'plugins { ... }' DSL if they specify explicit versions, even if the versions are equal.
         Please add the Kotlin plugin to the common parent project or the root project, then remove the versions in the subprojects.
         If the parent project does not need the plugin, add 'apply false' to the plugin line.
    My root 
    build.gradle.kts
     does not have a plugin block and my KMM module has the plugin block as follows.
    plugins {
        kotlin("multiplatform") version Versions.kotlin
        application
        kotlin("plugin.serialization") version Versions.kotlin
    }
    z
    • 2
    • 2
  • n

    NurBahnhof

    10/17/2020, 7:08 PM
    I have some third party package. I want to add some custom classes to this package nand have access to all package private variables without touching the jar so in my project I create a class file and declare "package thirdparty.package" . Can I do that? Does it work in Kotlin or does it have to be somehow in the same folder ?
    c
    • 2
    • 3
  • b

    Big Chungus

    10/17/2020, 7:53 PM
    Does anyone have a link to Google's kotlin annotation processor mentioned in one of the talks of 1.4 event? Can't find it anywhere.
    j
    f
    • 3
    • 8
  • w

    william

    10/17/2020, 9:07 PM
    is there a way to ignore warnings for an entire project / module? FlowPreview in my case
    m
    • 2
    • 3
  • x

    xxfast

    10/18/2020, 5:43 AM
    Anyone got any recommendations for graph libraries in kotlin? Google’s guava.graph seems enticing, but lack of first class support for kotlin seems less appealing
    m
    n
    • 3
    • 2
  • t

    Tomasz Krakowiak

    10/18/2020, 11:06 AM
    Hello I am trying to create IR plugin that generates object. Anyone has experience with it?
    k
    • 2
    • 2
  • g

    Gieted

    10/18/2020, 1:44 PM
    Hi, what is recommended way to manipulate files on desktop native?
    l
    • 2
    • 1
  • d

    Daniel

    10/18/2020, 3:37 PM
    Hi, I'm running into this error when trying to use
    async
    Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
    public fun <T> CoroutineScope.async(context: CoroutineContext = ..., start: CoroutineStart = ..., block: suspend CoroutineScope.() → TypeVariable(T)): Deferred<TypeVariable(T)> defined in kotlinx.coroutines
    I'm not sure how much I can pare down my example, because it seems pretty specific to what I'm trying to do. Here's essentially the function
    suspend fun getTile(params: SomeType): GetTileResponse {
            val cached = tileCache.get(params)
            if (cached != null) {
                return GetTileResponse.Available(cached)
            }
    
            val request = GetTileRequest(params)
    
            val deferred = async {
                makeRemoteRequest()
                .map { convertIntoResponse(it) }
            }
    
            return GetTileResponse.Loading(deferred)
        }
    If I ask kotlin to generate an implementation of async, I get something which seems to look very similar to the definition of async (https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html)
    private fun async(block: suspend CoroutineScope.() -> Either<GetTileError, Bitmap>): Deferred<Either<GetTileError, Bitmap>> {
            TODO("Not yet implemented")
        }
    a
    • 2
    • 14
  • s

    Simon Lin

    10/19/2020, 6:41 AM
    How to split a list to sub list with random size? input:
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    and random sub list size range from 0 to 4. output:
    [0, 1]
    [2, 3, 4, 5]
    [6]
    []
    [7, 8]
    []
    [9, 10]
    Each sub list size is random.
    p
    k
    e
    • 4
    • 6
  • e

    Edoardo Luppi

    10/19/2020, 9:54 AM
    Hi everyone. Currently I'm doing this
    providers.forEachIndexed { index, provider ->
      if (index == 0) {
        whatsNewPanel.setProvider(provider)
      }
      ...
    Is there a function/extension which lets me move that
    whatsNewPanel.setProvider(provider)
    in a separate space? Possibly in the same call chain
    m
    • 2
    • 1
  • s

    spand

    10/19/2020, 10:59 AM
    When delegating "build" in IDEA to gradle.. can I configure that somehow? I had hoped I could create run configuration for
    gradle build
    and IDEA would use it on build. Anyone tried something similar? I guess what I would like is the ability to set a custom
    -P
    or
    -D
    property for IDEA tasks
    v
    • 2
    • 11
  • h

    hallvard

    10/19/2020, 11:08 AM
    Is there a way to use the very handy
    lateInitVar.isInitialized()
    from java?
    r
    v
    +2
    • 5
    • 16
  • n

    Nick

    10/19/2020, 5:20 PM
    Hello people 🙂! In our companys closed chat we have been arguing with kotlin developers about how is it safe to remove intristics calls with proguard in release builds. I think that removing this checks brings undefined behaviour, because method body will start to execute before potential NPE, for example:
    fun f(a: String){
      sendData()
      //some a.length call (throws NPE)
    }
    with intrictics removed 'sendData' method will be executed. Another persons position is that business logic should be explicitly checked with some require(a!=null) check and developers should not rely on intrictics. What do you think?
    a
    j
    • 3
    • 3
  • d

    Daniel

    10/19/2020, 6:03 PM
    Hi I need an identifier for a cache that is based on four strings and two ints. I need to do this without allocating (because I'll generate many of them in a tight loop). I think that java's hashCode for strings is always the same for the same characters, but I'm not quite sure how to combine multiple hashCodes
    n
    m
    • 3
    • 28
  • d

    Daniel

    10/19/2020, 6:20 PM
    I'm planning to use this function to combine hashCodes. Does it make sense?
    fun bitLength(n: Int) = floor(log2(n.toFloat())).toInt() + 1
    
    fun combine(vararg numbers: Int): Int {
        var total = 0
        var prevBitLength = 0
        
        for (num in numbers) {
            total += num shl prevBitLength
            prevBitLength += bitLength(num)
        }
        
        return total
    }
    d
    n
    n
    • 4
    • 23
  • s

    Simon Lin

    10/20/2020, 7:21 AM
    Why I can’t convert a String (number with decimal) into Int directly?
    fun main() {
        val stringDouble = "420.0"
        val int = stringDouble.toIntOrNull()
        assert(int != null) // failed
    }
    b
    j
    n
    • 4
    • 5
  • h

    Hai Tran

    10/20/2020, 10:00 AM
    I’m trying add kotlinx-serialization(and something pure kotlin library) dependencies for KMM project, Is there a need to add for each platform(Android/iOS) separately, or just add COMMON dependencies?
    m
    • 2
    • 36
  • p

    Peter Ertl

    10/20/2020, 10:58 AM
    is there something like list-of-jobs.joinAllOrThrowOnFirstExceptionWhateverHappensFirst?
    m
    s
    • 3
    • 6
Powered by Linen
Title
p

Peter Ertl

10/20/2020, 10:58 AM
is there something like list-of-jobs.joinAllOrThrowOnFirstExceptionWhateverHappensFirst?
m

Marc Knaup

10/20/2020, 11:00 AM
Just launch all jobs inside a
coroutineScope { … }
. It will automatically wait until all Jobs are completed or throw on first job failure.
☝️ 1
p

Peter Ertl

10/20/2020, 11:01 AM
coroutineScope { repeat(100) { launch { …. one job of many }}} // --> will automatically have this behavior?
m

Marc Knaup

10/20/2020, 11:21 AM
Yes
s

Stephan Schroeder

10/20/2020, 3:54 PM
and the first exception will also cancel all the other coroutines you started. Structured concurrency for the win 😎
👍 1
p

Peter Ertl

10/21/2020, 10:15 AM
thank you very much stephan (or probably “Vielen Dank” since your name sounds German)
and thanks Marc
View count: 15