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

    Ayfri

    02/09/2022, 10:13 PM
    Just a quick question, is there any more simpler way to write
    list.sortedBy { it }
    , for a list of strings or numbers ? I know it's already pretty short but the fact that there's only
    it
    in the lambda feels kinda wrong
    j
    e
    • 3
    • 3
  • b

    brabo-hi

    02/10/2022, 4:44 AM
    Hi all, how fun is kotlin functional? given a list of items how can you return a list grouped by consecutive items? [“Apple, Bananas, Bananas, Orange” ] should return [(apple, 1), (bananas, 2), (orange, 1) ] I know you could use group by , but it does not respect the order
    e
    r
    +2
    • 5
    • 7
  • k

    Kenneth

    02/10/2022, 11:21 AM
    Is there an easy way to go from Instant to XMLGregorianCalendar in Kotlin?
    s
    s
    t
    • 4
    • 5
  • r

    Rescribet

    02/10/2022, 1:54 PM
    What would be the best way to generate Kotlin programs? E.g. an AST API which can be used to generate kt files or do compiler validation with
    t
    • 2
    • 3
  • j

    james

    02/11/2022, 7:56 AM
    I am trying to understand how I can rebuild a tree from a flat list which is given to me by an API. My model is simple:
    data class Reply(id: Int, parentId: Int, replies: List<Reply>)
    ... and I'm attempting to:
    {
        "replies": [
            { id: 1, parent: 0 }  <- turn this     1
            { id: 2, parent: 1 }     into this ->  └── 2
            { id: 3, parent: 2 }                       ├── 3
            { id: 4, parent: 3 }                       │   └── 4
            { id: 5, parent: 2 }                       ├── 5
            { id: 6, parent: 2 }                       ├── 6
            { id: 7, parent: 2 }                       └── 7
        ]
    }
    does anyone have any experience in "unflattening" a list into a tree like this? I start out by using
    associateBy
    on my flat list and turn it into a mutable map, at which point I iterate the flat list itself and append the current item to any value in the map whose
    id
    matches the current iterator item's
    parentId
    . doing this I end up with a list where the first and second levels are correct, but third and deeper are empty I've spent about 10 hours on this over the past 3 days and I've really gotten nowhere, just going in circles really. would love some guidance from anyone who has done this kind of thing with Kotlin
    👍 1
    j
    r
    +2
    • 5
    • 10
  • g

    Gustav Elmgren

    02/11/2022, 11:15 AM
    Hi everyone! Lets say I have the following structure:
    class Test {
        val firstValue: String
        val secondValue: Long
    }
    
    class TestWrapper {
        val firstValue: Wrapper<String>
        val secondValue: Wrapper<Long>
    }
    Would it be possible somehow to create a common interface/class for these two classes? For example, if it would be possible, using union types:
    interface InterfaceTest<T : Wrapper<T>, T>
    But given that is not possible, is it some other way Kotlin can handle this?
    e
    j
    +2
    • 5
    • 21
  • l

    Luis

    02/11/2022, 3:09 PM
    Hi everyone! If some 3rd party lib is providing the following couple of functions:
    fun find(session: Session, query: Query) {}
    fun find(query: Query) {}
    Is there a cleaner way than this to pick which one to use?
    fun caller(session: Session?) {
        val query = Query()
        if (session == null) {
            return find(query)
        }
        return find(session, query)
    }
    Thanks!
    a
    t
    • 3
    • 8
  • x

    xii

    02/11/2022, 4:17 PM
    i have a question about suspend functions and await (thread)
    v
    • 2
    • 5
  • j

    Johannes Fahrenkrug

    02/11/2022, 6:09 PM
    I have a very simple question. I have a kotlin multiplatform gradle project. I use VS Code and the command line to run and build it. When I run
    ./gradlew --version
    I get
    ------------------------------------------------------------
    Gradle 6.8.1
    ------------------------------------------------------------
    
    Build time:   2021-01-22 13:20:08 UTC
    Revision:     31f14a87d93945024ab7a78de84102a3400fa5b2
    
    Kotlin:       1.4.20
    Groovy:       2.5.12
    Ant:          Apache Ant(TM) version 1.10.9 compiled on September 27 2020
    JVM:          11.0.10 (JetBrains s.r.o. 11.0.10+0-b96-7249189)
    OS:           Mac OS X 12.1 aarch64
    Where does the Kotlin version
    1.4.20
    come from and how to I update that version? I don’t have that version specified anywhere in my project. In fact, I’m using
    1.6.20
    for kotlin-multiplatform. How do I set Kotlin to the same version? Thanks!
    j
    v
    • 3
    • 3
  • m

    Milse113

    02/11/2022, 8:53 PM
    Hey — I have a module system in my project which allows me to write generalized extensions and features for my project. At the moment I register these modules by manually adding it to a list in a manager class. I want to try to clean up this process a bit by adding an
    @Register
    annotation which allows the manager class to automatically register it. While I could do this with reflection, I want to be able to include and exclude some of these modules at compile-time (IE if I have a beta vs prod build), and preferably also generate the list at compile-time. from what I can tell, the best way to do this is with a compiler plugin, but I can’t find a framework which allows this as most major Kotlin compiler plugin libraries don’t allow modifying existing files, but instead only creating new ones. How should I go about doing this?
    j
    • 2
    • 8
  • a

    Andrew Reed

    02/12/2022, 10:42 AM
    Hi, i have a KMM library which uses cocoapods for the ios targets (arm64, simarm64) and when trying to compile its failing because of Unresolved reference: cocoapods BUT when i set one ios target, then it seems to work, but obviously i need to support multiple targets.
    v
    s
    • 3
    • 24
  • v

    Vampire

    02/12/2022, 8:09 PM
    If you have a Java interface
    public interface Transformer<OUT, IN> {
        OUT transform(IN in);
    }
    And a Java method
    filter(Transformer<String, String> var1)
    And Kotlin wrongly assumes the second parameter to be non-
    null
    . How can you call it with a lambda that returns
    null
    ?
    j
    e
    j
    • 4
    • 20
  • t

    Turyin

    02/13/2022, 7:33 PM
    What resources do you have for “compose for desktop” beginners?
    j
    • 2
    • 2
  • t

    Turyin

    02/13/2022, 7:53 PM
    And what resources would you recommend for newcomers to Kotlin because YouTube isn't working out
    j
    p
    s
    • 4
    • 5
  • a

    Ayfri

    02/14/2022, 5:26 AM
    Hi, can I create an extension static method to all classes ? I tried this
    inline fun <T : Any> T.create(block: T.() -> Unit) = jso(block)
    But the receiver type is of the companion object of the class and doesn't work if the class doesn't have any companion object, so this is not what I want I want to be able to do
    AnyClass.create { }
    and have the receiver equal to the receiver when doing
    AnyClass().apply { }
    i
    t
    • 3
    • 5
  • e

    Eivind

    02/14/2022, 8:22 AM
    Hi, Does Jetbrains have a slack channel for IDEs too? I have questions about Rider for .Net and code style
    r
    s
    • 3
    • 2
  • n

    Nahuel Canavy

    02/14/2022, 8:51 AM
    Hello, I'm new to Kotlin and I'm trying to code an application with the IDE AndroidStudio. I would like to recover a csv file send by an other application thus I would like that my application shows in the selection area of the other application ( like Gmail in the ScreenShot). Do you you know how I can do this ? Or do you have any link that explain how to do it ?
    n
    • 2
    • 7
  • z

    zain

    02/14/2022, 9:38 AM
    Need help in building the algorithm, looking for an optimum version of it,
    The logic for creating the fixture is in pairs. You have to form a pair of two teams in a random                                     
    fashion. For example - If I have 4 teams - T1, T2, T3, T4. I can have: 
     
    (T1 vs T2) & (T3 vs T4) 
    
    OR 
    (T1 vs T3) & (T2 vs T4) 
    
    OR 
    (T1 vs T4) & (T2 vs T3) 
     
    *Your function should accept any number n, where n is an even number > 0 and return you n/2                               
    pairs/tuples*
    j
    e
    • 3
    • 30
  • n

    Naveed

    02/14/2022, 7:37 PM
    Hello, is it currently possible to use Compose for Kotlin Multiplatform to create a common module which can provide Composables to both Kotlin/JVM for Desktop and Kotlin/JS for Web modules? The use case for this would be to create a UI that is consistent across both Desktop and Web without having to recreate UI models separately per platform. I am aware data models can be designed and shared using the architecture stated above but am unsure whether shared composables can be used in the same way. Is it possible to have a module with both jvm + js targets which imports and compiles "org.jetbrains.compose" and creates all the artifacts needed for both JVM and JS modules?
    🇳🇴 1
    • 1
    • 1
  • a

    Ayfri

    02/14/2022, 10:21 PM
    Hi, I fell into a little types mangling while doing a library for Kotlin/JS, I typed some events types that uses
    eventemitter3
    library with a pretty ugly (I think) but simple solution
    sealed interface DisplayObjectEvents<T : Any> {
    	object added : DisplayObjectEvents<Container>
    	object click : DisplayObjectEvents<FederatedPointerEvent>
    	object clickcapture : DisplayObjectEvents<FederatedPointerEvent>
    	object destroyed : DisplayObjectEvents<Nothing>
    	object mousedown : DisplayObjectEvents<FederatedPointerEvent>
        ...
    	(there are almost 100 elements in total)
    }
    But I want to be able to use it like that
    myObject.on<DisplayObjectEvents.added> { // it is Container here }
    , so I created this
    inline fun <reified T : DisplayObjectEvents<T>> DisplayObject.on(noinline callback: (T) -> Unit) = on(T::class.simpleName!!, callback as ListenerFn, null)
    // ListenerFn is just a function type that take Any arguments Any number of time
    // Which is the default type for my library for events in TypeScript
    But
    myObject.on<DisplayObject.added> {
        // it is of type DisplayObject.added
    }
    What I've done wrong ?
    r
    • 2
    • 5
  • j

    james

    02/14/2022, 10:38 PM
    in Kotlin, what is the most efficient way to replace many strings inside another string? what I mean is, I could do:
    originalString
        .replace("cat", "dog")
        .replace("goat", "cow")
        .replace("horse", "pig")
    ..but chaining those
    replace()
    calls would become very inefficient I assume, even if I created a map to iterate over. does Kotlin have any functions I can use to do a single pass over
    originalString
    and replace X number of items?
    e
    a
    +2
    • 5
    • 7
  • z

    zain

    02/15/2022, 9:53 AM
    Can we do a conditional chain in Kotlin? or ignore it and go to the next operator?
    private fun simulateFixtures(list: List<List<Team>>) = list.map { fixture ->
        fixture.toList().random()
    }.shuffled().chunked(2)
    s
    j
    +2
    • 5
    • 13
  • l

    Lukasz Kalnik

    02/15/2022, 2:59 PM
    How do I convert a
    List<Int>
    to an
    IntArray
    (not
    Array<Int>
    )?
    j
    g
    • 3
    • 5
  • l

    Lukasz Kalnik

    02/15/2022, 4:32 PM
    Is there a ready function in std lib which maps a value from one range (say
    0..1
    ) to another range (say
    1_000..5_000
    )? Basically the equivalent of this:
    fun getRangeValueAtInterval(start: Int, end: Int, interval: Float): Int =
        start + (interval * (end - start)).roundToInt()
    j
    • 2
    • 2
  • d

    Dan O'Brien

    02/15/2022, 8:30 PM
    I have a class that does not take any parameters when instantiating, but it has a number of properties I need to set after. Is there any clean way to use a lambda or similar to set all of the properties inside one
    {}
    block after instantiating the class?
    j
    • 2
    • 3
  • j

    Jan

    02/15/2022, 9:17 PM
    I'm curious why does Kotlin create a class implementation instead of default methods when creating an interface with methods that have a body? (I now you can change that)
    t
    j
    +3
    • 6
    • 11
  • t

    TheOnlyTails

    02/16/2022, 7:32 PM
    Hi! How can I use generic type parameters in lambda types? For example:
    val list = listOf<<T>(x: T) -> Unit>()
    v
    j
    +3
    • 6
    • 15
  • j

    Jerv Norsk

    02/17/2022, 9:13 AM
    Hi everyone I would like to try to work with the kotlin AST but I have no idea where to start. Do you have any suggestions / links?
    j
    t
    • 3
    • 3
  • u

    Uğur

    02/17/2022, 1:59 PM
    Hi. I have some questions about my Kotlin carrier. Is there an expert to help me? 😊
    a
    l
    • 3
    • 6
  • b

    Bernard Ng

    02/17/2022, 3:42 PM
    Hello everyone, I'm coming from a PHP ecosystem where we have packagist.org as a repository of all PHP packages, is there something similar for Kotlin ? Thanks
    :kotlinnew: 1
    r
    e
    f
    • 4
    • 4
Powered by Linen
Title
b

Bernard Ng

02/17/2022, 3:42 PM
Hello everyone, I'm coming from a PHP ecosystem where we have packagist.org as a repository of all PHP packages, is there something similar for Kotlin ? Thanks
:kotlinnew: 1
r

Richard Gomez

02/17/2022, 3:43 PM
Maven Central is the main repository for all JVM languages: https://search.maven.org/
➕ 1
b

Bernard Ng

02/17/2022, 3:48 PM
Thanks @Richard Gomez
e

elizarov

02/18/2022, 9:38 AM
Also https://package-search.jetbrains.com/
👍 2
f

flygerian.eagle

03/14/2022, 3:25 AM
@Bernard Ng Broda mmi, how far? The road is smooth.. Condition mek crayfish bend: Happy coding o!
View count: 3