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

    ursus

    07/09/2022, 9:24 AM
    is adding a function parameter with default value an ABI change?
    e
    • 2
    • 1
  • a

    Adam S

    07/10/2022, 6:47 AM
    tl;dr: Is there ordered queue with file-based storage for coroutines? I've got a Ktor socket server that captures log messages from a TCP port, and forwards them to a Kafka topic. However the connection to Kafka is unstable, so I need to store the logs locally, and then forward them to Kafka once the connection is up. I think the best solution is a local file-based ordered store that I can put messages into with a
    MutableSharedFlow<String>
    , and then another
    SharedFlow<String>
    that in another coroutine awaits new messages from the file-store and forwards them to the Kafka topic (I'm using Kotlin/JVM 1.7, Ktor 2.0, Kakfa 3.2)
  • c

    Chris Cordero

    07/10/2022, 11:05 PM
    Could anyone help me understand why the compiler complains here:
    import com.fasterxml.jackson.core.type.TypeReference
    import java.util.function.Supplier
    
    class Bar(val x: Int)
    
    fun foo(whatever: Supplier<TypeReference<out Bar>>) {}
    
    fun main() {
        val typeRef = object : TypeReference<Bar>() {}
        val supplier = Supplier<TypeReference<Bar>> { typeRef }
        foo(supplier) // expected Supplier<TypeReference<out Bar>>, got Supplier<TypeReference<Bar>>
    }
  • c

    Chris Cordero

    07/10/2022, 11:06 PM
    but it accepts this:
    import java.util.function.Supplier
    
    class Bar(val x: Int)
    
    fun foo(whatever: Supplier<out Bar>) {}
    
    fun main() {
        val supplier = Supplier<Bar> { Bar(42) }
        foo(supplier) // compiler happy
    }
    r
    • 2
    • 1
  • m

    Manuel Dossinger

    07/11/2022, 7:35 AM
    Is there something like filterNotNull for map keys? Such that a map with nullable key type is transformed to a map with not-nullable key type
    e
    • 2
    • 2
  • t

    thana

    07/11/2022, 8:45 AM
    is there some neat way to publicly expose a read-only view on a private, mutable collection? i always end up with something like
    private val mutable = mutableListOf<Something>()
    val readonly: List<Something> = mutable
    which is kinda ugly
    s
    k
    • 3
    • 6
  • l

    Landry Norris

    07/11/2022, 4:14 PM
    I wrote this convenience function for testing if a double is within a range.
    fun assertWithin(expected: Double, actual: Double, tolerance: Double) {
        val message = "Difference of ${actual-expected} is out of range. " +
                "Expected $expected, got $actual"
        if(abs(expected-actual) > tolerance) println(message)
        assertTrue(abs(expected-actual) <= tolerance, message)
    }
    I see this message in the console, though
    Difference of -6.004799503160669E14 is out of range. Expected 0.75, got -6.004799503160661E14
    How could (-6.004799503160661E14)-(0.75) be equal to (-6.004799503160661E14)? Edit: misread the exponent. subtracting 0.75 from 6*10^14 is essentially 6*10^14
    k
    • 2
    • 6
  • r

    reactormonk

    07/11/2022, 4:16 PM
    Does the concept of "an array of exactly 4 elements" exist in the kotlin type system? As an argument to my function.
    l
    k
    • 3
    • 3
  • c

    Colton Idle

    07/12/2022, 5:11 AM
    This might come off as a bit crazy. But I inherited a project that has a mapper file that has like a 3,000 line when statement. There's only maybe about 300 when conditions, and each "mapper" is roughly 10 lines of code. My problem is that the IDE is suppppppper slow when this file is open. I can barely do anything. As a temporary measure I want to just split this file in half, and then half again. Which leads me to my question. Is there an easy/clever way to split a when statement across multiple files or do I have to refactor this, condition by condition. This wouldn't necessarily be a problem if the IDE could actually keep up with refactor tools. I just get the rainbow ball on macOS and have to wait like 3 minutes after every refactor. There has to be a better way. lol
    😱 1
    f
    e
    +2
    • 5
    • 5
  • l

    Loney Chou

    07/12/2022, 5:57 AM
    I have a function that runs on main thread, which cannot be modified, like this:
    fun calculate(): Int
    And inside it I need to call a suspend function. How to do that?
    runBlocking
    ?
    r
    • 2
    • 6
  • n

    nkiesel

    07/12/2022, 6:58 AM
    given a map with possibly repeated values, is the following best way to reverse it (to a Map<V, List<K>>)
    fun <K, V> Map<K, V>.reverse(): Map<V, List<K>> = entries.groupBy { it.value }.map { it.key to it.value.map { it.key } }.toMap()
    d
    k
    • 3
    • 4
  • r

    reactormonk

    07/12/2022, 12:24 PM
    Is there a library that implements the Debug / inspect functionality similar to the Rust
    inspect
    ? Where you get a full dump of a class, not just the
    toString
    k
    m
    d
    • 4
    • 6
  • c

    Ciox

    07/12/2022, 1:41 PM
    Would you recommend someone to do DSA interview in Kotlin? Or I should stick to traditional c#, Java, c/cpp or python
    j
    • 2
    • 4
  • l

    Landry Norris

    07/12/2022, 7:30 PM
    Is there a reliable way to determine the class of a reified generic, including typedefs? I tried a when(T::class), but I can’t use X::class when X is a typedef. I would like to distinguish X and Y, where X and Y are both typedefs for class Z.
    e
    • 2
    • 12
  • s

    Stylianos Gakis

    07/13/2022, 9:07 AM
    I’m writing a block comment over a function and would like to use the nice formatting we get inside IntelliJ. I got a table right now which looks something like this
    * | name | required | description | default value | example |
     * | :--- | :--- | :--- | :--- | :--- |
     * | name | ✅ | desc | ❌ | example |
    It renders as I would expect, with the items left-aligned and everything, but everything is way too close to each other. Is there a way in this formatter to make it look like an actual table? Preferably keep some dividers vertically and horizontally across the items, but if not at least some way to force more space between the items.
    a
    • 2
    • 4
  • r

    reactormonk

    07/13/2022, 11:30 AM
    Where do I put worksheets so I can use dependencies from the current project? When I put them into
    src/main/java
    , I get https://stackoverflow.com/questions/59366460/org-jetbrains-kotlin-resolve-lazy-nodescriptorfordeclarationexception-descripto
  • t

    Ties

    07/13/2022, 3:10 PM
    Hi all, just a general design choice question about value classes. If I create a value class, I am only allowed to have exactly 1 constructor parameter. If I then use this type, I still have to treat it as a class with a variable. If the compiler knows Foo only has 1 variable, and it knows its type. why does the compiler make me use myFoo.value instead of just myFoo?
    @JvmInline
    value class Foo(val value : Int) {
    }
    
    //This doesnt work
    fun bar(myFoo : Foo) : Int{
       return myFoo + 1
    }
    
    //This works
    fun bar(myFoo : Foo) : Int{
        return myFoo.value + 1
    }
    r
    c
    +3
    • 6
    • 69
  • r

    reactormonk

    07/14/2022, 8:09 AM
    Can I express this code without having to have the
    TLV<T>
    signature, and just use
    TLV
    to represent it, if I'm using the interface to designate the type?
    sealed interface TLV<T> {
        val value: T
        val type: Byte
    }
    object TLVNULL: TLV<Unit> {
        override val type: Byte = 0x00
        override val value: Unit = Unit
    }
    data class TLVNDEF(override val value: NdefMessage): TLV<NdefMessage> {
        override val type: Byte = 0x03
    }
    data class TLVProp(override val value: ByteArray): TLV<ByteArray> {
        override val type: Byte = 0xFD.toByte()
    }
    object TLVTerminator: TLV<Unit> {
        override val type: Byte = 0xFE.toByte()
        override val value: Unit = Unit
    }
    y
    • 2
    • 1
  • c

    Colton Idle

    07/14/2022, 7:18 PM
    I have an enum defined, and I want to get the enum from the key that I get from another source (a network response to be exact). The manual mapping seems fine, but is there another way (thats idiomatic) to do this kind of thing?
    enum class Foo(val key: String, val userName: String) {
      Bar("bar_item", "Bar For You"),
      Baz("baz_item", "Baz For Me"),
      OTHER("other", "Other"),
    }
    
    fun getTheFoo(key: String): Foo {
      return when (key) {
        "bar_item" -> Foo.Bar
        "baz_item" -> Foo.Baz
        "other" -> Foo.OTHER
        else -> Foo.OTHER
      }
    }
    l
    e
    +2
    • 5
    • 8
  • m

    Matthieu Stombellini

    07/14/2022, 8:37 PM
    Hi! I'm not sure of which channel is best for this, but I'm trying to get
    provideDelegate
    to work with generic output types. Basically, what I'm trying to do is the following setup:
    class Producer {
        inline fun <reified T> create(): ReadOnlyProperty<Any, T> {
            println("Creating a property with create(), return type is ${T::class}")
            TODO()
        }
        
        inline operator fun <reified T> provideDelegate(thisRef: Any, prop: KProperty<*>): ReadOnlyProperty<Any, T> {
            println("Creating a property with provideDelegate, return type is ${T::class}")
            TODO()
        }
    }
    
    class MyClass(producer: Producer) {
        val one: String by producer.create()
        //val two: String by producer
    }
    While the
    val one
    works perfectly fine, if I uncomment
    val two
    , it no longer compiles. Is there any way to do this? Kotlin Playground link: https://pl.kotl.in/vXOAoeauS Compilation fails with:
    Property delegate must have a 'provideDelegate(MyClass, KProperty<*>)' method. None of the following functions is suitable: public final inline operator fun <reified T> provideDelegate(thisRef: Any, prop: KProperty<*>): ReadOnlyProperty<Any, ???> defined in Producer
    y
    • 2
    • 1
  • f

    frogger

    07/15/2022, 7:57 AM
    I want to build a simple web admin panel with kotlin. I suck at (web) design so I prefer to have a solid UI library. The web resources should ideally run from a static webspace (not an application server). (All backend api requests will be 3rd party APIs anyhow). What would you recommend?
  • l

    Lukasz Kalnik

    07/15/2022, 8:42 AM
    Is there no smart cast in case of `OR`ed null checks inside of
    if
    ?
    val selectedScene1: String? = // ...
    val selectedScene2: String? = // ...
    if (selectedScene1 != null || selectedScene2 != null) {
        val sceneToFind: String = selectedScene1 ?: selectedScene2!! // The !! are necessary to make this work
    }
    m
    e
    • 3
    • 6
  • j

    João Gabriel Zó

    07/15/2022, 4:58 PM
    is there a youtube channel I could check for more advanced kotlin?
    👀 1
    s
    • 2
    • 1
  • m

    martmists

    07/17/2022, 12:33 AM
    why am I unable to import this extension function?
    import io.github.gunpowder.api.config
    doesn't resolve.
    y
    l
    • 3
    • 4
  • l

    Lukasz Kalnik

    07/18/2022, 9:33 AM
    Is there an online tool to pretty print the
    data class
    toString()
    output? I have a lot of nested data classes and when a test fails it's quite cumbersome to compare the linear outputs of the standard
    toString()
    implementation of a data class.
    j
    o
    v
    • 4
    • 11
  • l

    Lukasz Kalnik

    07/18/2022, 3:02 PM
    What is the idiomatic way of copying an immutable list with one element removed?
    mapNotNull { if (it == removeMe) null else it }
    doesn't support lists with nullable elements. In my case the elements have unique IDs, so I could also
    filter {}
    or
    dropWhile {}
    based on ID, but the names are not obviously suggesting that only one element gets removed. Do we have to do
    toMutableList().remove(removeMe).toList()
    ?
    j
    e
    +2
    • 5
    • 22
  • j

    Jiri Bruchanov

    07/19/2022, 3:35 PM
    anyone who would be able to help ? I think I have lost type safety using inline function with reified type, but not sure why
    l
    • 2
    • 9
  • d

    dimsuz

    07/19/2022, 4:30 PM
    Why does this
    if (true) 1 else if (false) { 2 } else { 3 }.also { println("hello") }
    if (true) 1 else { 3 }.also { println("world") }
    print only "world" and not "hello"? first one treats whole if/else as an expression why the latter one treats only else branch as an expression?
    e
    • 2
    • 2
  • n

    Nat Strangerweather

    07/19/2022, 6:06 PM
    Is it possible to zip 3 lists? I am zipping 2 here, but I would like to throw a list of icons into the mix. How would it work in Kotlin?
    @Composable
    fun ShowDropDown(
        openDropDown: MutableState<Boolean>,
        text: List<String>,
        destination: List<DirectionDestination>,
        navigator: DestinationsNavigator,
    ) {
        DropdownMenu(
            expanded = openDropDown.value,
            onDismissRequest = { openDropDown.value = false },
        ) {
            text.zip(destination)
                .forEach {
                    DropdownMenuItem(onClick = { navigator.navigate(it.second) },
                    text = { Text(it.first) })
                }
    
        }
    }
    l
    m
    • 3
    • 5
  • z

    Zinedine Bedrani

    07/19/2022, 6:58 PM
    Playing with Reflection API and property reference I tried something like this :
    data class Point(val x:Int, val y:Int)
    
     val p = Point(5,13)
    
       val getter1 = Point::x
       val getter2: (Point) -> Int  = Point::x
     
        println(getter1(p)) // 5
        println(getter2(p)) // 5
    What I don’t understand is why with getter1 I was able to get reflection information about x for example I could do something like :
    println(getter1.visibility) // PUBLIC
       println(getter1.returnType) // <http://kotlin.Int|kotlin.Int>
    while with getter2 I can’t, even if I use the
    @OptIn(ExperimentalReflectionOnLambdas::class)
    with
    println(getter2.reflect()?.returnType)
    the result is null.
    j
    • 2
    • 4
Powered by Linen
Title
z

Zinedine Bedrani

07/19/2022, 6:58 PM
Playing with Reflection API and property reference I tried something like this :
data class Point(val x:Int, val y:Int)

 val p = Point(5,13)

   val getter1 = Point::x
   val getter2: (Point) -> Int  = Point::x
 
    println(getter1(p)) // 5
    println(getter2(p)) // 5
What I don’t understand is why with getter1 I was able to get reflection information about x for example I could do something like :
println(getter1.visibility) // PUBLIC
   println(getter1.returnType) // <http://kotlin.Int|kotlin.Int>
while with getter2 I can’t, even if I use the
@OptIn(ExperimentalReflectionOnLambdas::class)
with
println(getter2.reflect()?.returnType)
the result is null.
j

Joffrey

07/19/2022, 7:03 PM
The types of
getter1
and
getter2
are not the same. By specifying a wider type on
getter2
, you're losing the specificities of the more precise type of
Point::x
(
KProperty1<Point, Int>
). Using the actual
KProperty
type comes with extra information. A simple analogy would be
val getter3: Any = Point::x
- do you expect to be able to access
visibility
and
returnType
here?
Using
.reflect()
on the
getter2
function will just give you a
KFunction
, not really information about the actual property
x
z

Zinedine Bedrani

07/19/2022, 7:08 PM
No I don’t Expect that but
(Point) -> Int
is a function type, so r`eflect()` should return
KFunction
, isn’t it ? so I don’t understand why reflect() doesn’t return
KProperty.Getter
in this case, or Am I wrong ?
Ah OK I see
View count: 4