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

    xii

    06/21/2022, 6:59 PM
    hey! Is there any way when using
    awaitAll()
    with different variables of different types for it to not be casted as Any?
    j
    e
    g
    • 4
    • 20
  • v

    Vaios Tsitsonis

    06/22/2022, 8:45 AM
    Hello! I have a question but I was not sure which was the appropriate channel to post it. I have a multi-module project and I noticed that in some modules I can not use the
    buildList
    ,
    buildMap
    , etc. due to
    Unresolved reference
    . In my gradle file I have added a stdlib dependency. So why does this happen? Does it need some extra configuration?
    j
    l
    • 3
    • 9
  • c

    cheeze2000

    06/22/2022, 10:51 AM
    hello, does anyone know a good test coverage gradle plugin for kotlin?
    j
    v
    • 3
    • 4
  • s

    Stephan Schroeder

    06/22/2022, 12:12 PM
    In the case of a maven project with Kotlin and Java side by side, the Kotlin docu (https://kotlinlang.org/docs/maven.html#compile-kotlin-and-java-sources) suggests this configuration
    <configuration>
        <sourceDirs>
            <sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
            <sourceDir>${project.basedir}/src/main/java</sourceDir>
        </sourceDirs>
    </configuration>
    but what do I do if I have a multi-module project?
    ${project.basedir}/src/main/kotlin
    lacks the module in it's path, doesn't it?
    v
    a
    • 3
    • 10
  • s

    sreich

    06/22/2022, 4:31 PM
    am i correct in thinking this is a false positive inspection on my mvn pom? updates says i am running plugin version 221-1.7.0-release-281-IJ5591.52
    Kotlin version that is used for building with Maven (1.7.0) differs from the one bundled into the IDE plugin (1.6.10)
    k
    • 2
    • 7
  • s

    sreich

    06/22/2022, 9:16 PM
    is there a feature in between it being a 'data' class and a normal class? how do i get kotlin to generate componentN's if it is not a data class?
    e
    a
    +2
    • 5
    • 10
  • u

    Ubed

    06/23/2022, 8:05 AM
    Hello! Can anyone tell me how to use posgtresql with jetbrains exposed as want to build a basic blog app using micronaut framework.
  • e

    Elizeu Silva dos Santos

    06/23/2022, 11:43 AM
    I have a huge file to read, more than 5GB. I need to do some transformation over each line, convert into my data object and than persist.
    File.forEachLine
    is a good choice for that?
    j
    • 2
    • 4
  • g

    Guilherme D. Fernandes

    06/23/2022, 5:48 PM
    Hello there... I'm new here and I very interested in learning about kotling... I'm curretly working with Salesforce and I wanted to create POC to integrate Salesforce with external systems using serveless APIs...
  • c

    cheeze2000

    06/24/2022, 1:55 AM
    does anyone know if
    b in a..c
    has the same performance as
    a <= b && b <= c
    ?
    s
    e
    +2
    • 5
    • 19
  • r

    Rodrigo Silva

    06/24/2022, 3:48 AM
    Is there any way to force a failure in the
    runCatching
    block like:
    runCatching {
         when (some_condition) {
             1 > failure
             else -> todo
    }
    y
    • 2
    • 1
  • j

    Joffrey

    06/24/2022, 1:23 PM
    Is there any way to get a "safe"
    is
    check on Kotlin/JVM, in the sense that it doesn't fail with
    NoClassDefFoundError
    if the class is not on the classpath? I would like to do something with an object if it's of a given type, with the smart cast, but I don't want it to fail if running on lower JDK that doesn't have that class, I just want the condition to be false, and the code to move on without trying to load the class.
    k
    e
    • 3
    • 7
  • c

    cheeze2000

    06/24/2022, 1:35 PM
    hello, jacoco says that this specific line has 6 branches. i can't figure out the missing branch, does anyone know?
    s
    • 2
    • 3
  • s

    sreich

    06/24/2022, 1:45 PM
    Is there a way to prevent developers from using kotlin-logging's logger.log("this $expensiveOperation()"), in favor of them doing logger.log { "this $expensiveOperation()" } ? https://github.com/MicroUtils/kotlin-logging
    c
    j
    • 3
    • 11
  • a

    Alfred Lopez

    06/24/2022, 5:35 PM
    Hello, The attached file contains a class that tests access to a block of code protected by a mutex. The pattern is I only want the first coroutine to access the protected block, by rerouting all subsequent calls using a condition on mutex.isLocked. I’m getting inconsistent behavior: at times all coroutines can access the block and at other times, they get rerouted. With some experimentation, if I delay launching coroutines, then the expected behavior is observed, however, this is not a practical solution. Is there a best practice around using Mutex? Thanks!
    import kotlinx.coroutines.*
    import kotlinx.coroutines.Dispatchers.Default
    import kotlinx.coroutines.sync.Mutex
    import kotlinx.coroutines.sync.withLock
    
    class TestMutex {
        val mutex = Mutex()
    
        suspend fun createJobs() {
            val job1 = CoroutineScope(Default).launch {
                println("Job1")
                acquireMutex("Job1")
            }
    
            val job2 = CoroutineScope(Default).launch {
                println("Job2")
                acquireMutex("Job2")
            }
    
            val job3 = CoroutineScope(Default).launch {
                println("Job3")
                acquireMutex("Job3")
            }
    
            joinAll(job1, job2, job3)
            println("Delaying for a bit...")
            delay(1000)
            println("Done")
        }
    
        suspend fun createJobs2() {
            CoroutineScope(Default).launch {
                repeat(3) {
                    CoroutineScope(Default).launch {
                        println("Job$it")
                        acquireMutex("Job$it")
                    }
                }
            }.join()
    
            println("Delaying for a bit...")
            delay(1000)
            println("Done")
        }
    
        suspend fun acquireMutex(id : String) {
            if (!mutex.isLocked) {
                mutex.withLock {
                    println("Got here...$id")
                }
            }
            else {
                println("I was directed to here...$id")
            }
        }
    }
    
    suspend fun main() {
        val testClass = TestMutex()
    
        println("First run...")
        testClass.createJobs()
    
        println("Second run...")
        testClass.createJobs2()
    }
    j
    • 2
    • 7
  • e

    elect

    06/24/2022, 6:13 PM
    given some constraints, I have to express some logic via boxed primitives It turns out I also have to collect them in a map, but different boxed instance of the same value (ie
    java.lang.Boolean(true)
    , which returns a boxed Boolean) won't be seen as different keys, that is they would be overwritten how can I solve it?
    v
    y
    k
    • 4
    • 10
  • k

    kotlinforandroid

    06/25/2022, 3:20 PM
    Is there a way to link two field states together?
    class FormField {
        var hasError: Boolean by mutableStateOf(false)
        var errorMessage: String? by mutableStateOf(null)
    
        // errorMessage != null iff. hasError == true
    }
    I tried contracts but one cannot reference variables that are not part of the contract method. I can't reason about
    this@FormField.errorMessage
    inside the implies boolean expression.
    y
    • 2
    • 6
  • s

    stvn

    06/26/2022, 10:31 AM
    Hi, Is there any guidelines when to use sequences vs normal collection operations with some dataset? Is there overhead if sequence is used with small dataset?
    s
    e
    p
    • 4
    • 7
  • k

    Klitos Kyriacou

    06/26/2022, 12:03 PM
    Is there a Kotlin convenience function that allows me to combine multiple Iterables into a single Iterable? In other words, can I do something like this:
    (list1 + list2).firstOrNull { it.matches(something) }
    but without eagerly iterating the lists and creating a new list from them? In other words, exactly like Guava's
    FluentIterable.concat(list1, list2)
    but more Kotlin-idiomatic?
    y
    n
    • 3
    • 8
  • r

    Rachel Carandang

    06/26/2022, 3:19 PM
    Question about use of lateinit var: I’ve only seen it used in class variables, but I recently came across it in a PR from someone new to Kotlin that used it inside a method call. What are the patterns and advice for using lateinit var inside methods? Or should it be avoided? Is the below use of lateinit valid?
    fun degreesToDirection(degrees: Float?): Direction {
                var smallestDistance: Float = Float.POSITIVE_INFINITY
                lateinit var direction: Direction
    
                degreesMapping.entries.forEach {
                    if (abs(it.value - (degrees ?: 0f)) < smallestDistance) {
                        direction = it.key
                        smallestDistance = (degrees ?: 0f) -  it.value
    
                    }
                }
    
                return direction
            }
    j
    j
    +2
    • 5
    • 19
  • a

    Andrew

    06/26/2022, 4:45 PM
    Possibly an IntelliJ question, is there a way to specify the root package name? I noticed if I have at least 1 class in the root and set the package to the name I want, then new files added there or sub directories automatically get the correct package name. Problem is if there are no classes in the root (only other sub-packages) then new files created in those don't get the correct package name and defaults to "package dirname" instead of "com.blah.modulename.dirname"
    s
    r
    • 3
    • 4
  • j

    Javier

    06/26/2022, 10:59 PM
    Is it possible to have nested lambdas which uses different
    DslMarker
    markers and picking the nested one? If I have two function with the same name, the outermost is used
    kotlin {
        android() // from kotlin
        multiplatform {
            common()
            android() // from kotlin, should be from multiplatform
            jvm()
        }
    }
  • l

    Lawrence

    06/26/2022, 11:25 PM
    is it possible to use ktor's type-safe requests to call an endpoint that needs a query param with no argument. I tried doing this:
    @Serializable
    @Resource("/end_point")
    class EndPoint(val query: String? = "")
    
    client().get(EndPoint())
    This results in:
    <http://base_url/end_point?query=>
    but I just want it to be
    <http://base_url/end_point?query>
    c
    • 2
    • 2
  • h

    Hassaan

    06/28/2022, 1:51 PM
    Does val property has a setter or not ? And is it equivalent to var property having private setter? E.g. 'val a = 2' is same as 'var a = 2 private set'
    j
    • 2
    • 2
  • n

    niqo01

    06/28/2022, 10:41 PM
    My project builds successfully in Kotlin 1.6.21. When upgrading to Kotlin 1.7.0 I get:
    [error] Compliance level '1.4' is incompatible with target level '11'. A compliance level '11' or better is required.
    It 's a simple gradle kotlin("jvm") project with:
    java {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }
    
    tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
        kotlinOptions.jvmTarget = "11"
    }
    I have no idea what Compliance level is
    i
    a
    • 3
    • 3
  • r

    Rodrigo Silva

    06/29/2022, 1:45 PM
    Hello all. I'm trying to understand why it's giving error, and how to fix it
    abstract class SomeClass {
    abstract fun someFunction(someParameter: String) : List<String?>
    }
    suspend inline fun <reified T : SomeClass> otherFunction(): Return<T> {
    val someAtt = T::someFunction("abc")
    }
    error: 
    left-hand side of callable referece cannot be a type parameter
    r
    • 2
    • 1
  • v

    v79

    06/29/2022, 8:04 PM
    I'm mighty confused. I've got a Kotlin 1.7 project, requiring JDK 18. It doesn't compile:
    e: D:\Development\Experiments\Pellet\server\src\main\kotlin\dev\pellet\server\PelletServerClient.kt: (8, 17): Unresolved reference: UnixDomainSocketAddress
    IntelliJ can see the import (no red squiggly lines). In Project Structure, I've chosen SDK `openjdk-18 java version "18.0.1"`(and I've also tried the cornetto variant of JDK18). The language level is set to 17 in InteilliJ and in the
    build.gradle.kts
    file. In IntelliJ's External Libraries view I can drill down to
    <http://java.base.java.net|java.base.java.net>
    and see the
    UnixDomainSocketAddress
    class (it was introduced in Java 16). But neither IntelliJ nor Gradle can find the class to compile it! (I've even dug into the JDK source folder, and it definitely exists!). Please, any ideas?
    k
    • 2
    • 4
  • r

    Rohan Maity

    06/30/2022, 7:03 AM
    Is there any way to store reified types to a variable?
    y
    r
    • 3
    • 11
  • o

    oday

    06/30/2022, 9:34 AM
    so I am trying to add a list of items to a list, there’s 1 item that I would like to either add (or not add) according to some flag
    r
    j
    y
    • 4
    • 6
  • k

    Kieran Wallbanks

    06/30/2022, 9:52 AM
    Has anyone been having issues using sealed classes/interfaces in Kotlin 1.7? I seem to constantly get runtime issues with classes throwing exceptions saying things like "X can't extend sealed class" when it has worked fine before. Plus compile-time issues where exhaustive when statements will break, saying they need an else when they definitely don't. They get fixed by doing completely clean builds so I was wondering if maybe there's an issue with compilation? I'm using the incremental kotlin compiler with classpath snapshots - could this be an issue with that?
    y
    d
    • 3
    • 6
Powered by Linen
Title
k

Kieran Wallbanks

06/30/2022, 9:52 AM
Has anyone been having issues using sealed classes/interfaces in Kotlin 1.7? I seem to constantly get runtime issues with classes throwing exceptions saying things like "X can't extend sealed class" when it has worked fine before. Plus compile-time issues where exhaustive when statements will break, saying they need an else when they definitely don't. They get fixed by doing completely clean builds so I was wondering if maybe there's an issue with compilation? I'm using the incremental kotlin compiler with classpath snapshots - could this be an issue with that?
y

Youssef Shoaib [MOD]

06/30/2022, 9:59 AM
For in-ide errors make sure your Kotlin plugin is up to date. Keep in mind that AFAIK some complex usages of sealed interfaces are just simply not understood by the exhaustiveness checker and so you will have to begrudgingly add an else.
k

Kieran Wallbanks

06/30/2022, 10:07 AM
Not getting any IDE errors - and it's not related to complexity either as the code compiles fine most of the time, it just breaks occasionally
d

dmitriy.novozhilov

06/30/2022, 10:10 AM
https://youtrack.jetbrains.com/issue/KT-45474/False-positive-NOELSEINWHEN-on-sealed-class-with-JPS-incremental-compilation
k

Kieran Wallbanks

06/30/2022, 10:18 AM
Would that be the same issue that causes it to fail at runtime too?
d

dmitriy.novozhilov

06/30/2022, 10:21 AM
Hm, no Issue I mentioned is only about incremental compilation Can you please create another one for your case?
k

Kieran Wallbanks

06/30/2022, 10:21 AM
Sure, I'll open an issue whenever it happens again. Very rare to occur though, I can't manage to reproduce it reliably at all
:tnx: 1
View count: 13