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

    Daniele B

    09/23/2021, 4:52 PM
    I can’t find
    ByteBuffer
    in Kotlin MultiPlatform. Is there anything similar I can use?
    p
    • 2
    • 2
  • e

    Endre Deak

    09/23/2021, 8:38 PM
    Please direct me to the right channel, but here’s the question:
    // this delegation works
    
    interface A { fun foo() }
    interface B { fun bar() }
    
    class AImpl() : A { override fun foo() = println("default foo") }
    class BImpl(private val a: AImpl) : B, A by a { override fun bar() = println("bar") }
    
    // ==============
    
    // how could I do a delegation for an inherited interface?
    interface A { fun foo() }
    interface B : A { fun bar() }
    
    class AImpl() : A { override fun foo() = println("default foo") }
    // no idea how to delegate
    class BImpl(private val a: AImpl) : B by a { override fun bar() = println("bar") } // ?
    r
    s
    • 3
    • 8
  • s

    suhas

    09/24/2021, 2:35 AM
    I am trying to understand how does this works.
    list.sortedWith(compareBy ({
        when(it.state) {
           A -> -1
           B -> 0
           C -> 1
       }
    }))
    This returns a list were all the elements with state A come first, followed by B and then followed by C. I am just not able to wrap head around this though. I understand how comparable works by overriding compareTo function and comparing two objects that the function gets. But not this. Can someone please explain this to me :)
    e
    c
    • 3
    • 4
  • s

    Simon Lin

    09/24/2021, 4:23 AM
    How can we remove items from specify position to end? for example:
    list: ["a", "b", "c", "d", "e", "f", "g"]
    give specify position: 3
    result: ["a", "b", "c"]
    e
    • 2
    • 3
  • d

    Danish Ansari

    09/24/2021, 7:27 AM
    Quick question regarding extension functions: Let's say if I add 1000 extensions functions in a
    String
    (just a scenario), so does that have any impact on performance? Just want to understand how exactly extension functions work and if there's any cost (or disadvantage) in using it that I should be aware of.
    j
    r
    • 3
    • 8
  • d

    Daniel Svensson

    09/24/2021, 8:08 AM
    Is full Java 17 LTS support scheduled for a 1.5.x release, 1.6.0 release, or later?
    👀 1
    d
    a
    • 3
    • 12
  • a

    antoniomarin

    09/24/2021, 10:59 AM
    Morning all, quick one regarding generic types. I know this is a safe check (as I have only one generic here), but Kotlin will still complain about it, any way how to improve this?
    data class Test<T>(
        val key: String,
        val additionalData: T
    )
    
    inline fun <reified T> Test<*>.checkSafeCast(): Test<T>? {
        return if (this.additionalData is T) {
            this as Test<T> // Unchecked cast
        } else {
            null
        }
    }
    j
    • 2
    • 3
  • a

    Ayden

    09/24/2021, 2:21 PM
    intervals = [[1,3],[2,6],[8,10],[15,18]]
    Arrays.sort(intervals, compareBy { it[1] })
    Hi guys, may i know how can i sort it in descending order based on the first index?
    a
    l
    j
    • 4
    • 4
  • b

    Brian Donovan

    09/24/2021, 3:42 PM
    “Normally, if you write a Kotlin function with default parameter values, it will be visible in Java only as a full signature, with all parameters present.” What is a signature?
    k
    j
    +4
    • 7
    • 14
  • k

    knthmn

    09/25/2021, 4:57 AM
    In a command line / JVM app (with coroutines), how to listen for SIGTERM and do some cleanup?
    fun main() = runBlocking {
        // ... launch some stuffs
        // wait for ctrl-C, how?
        cleanup()
        cancel()
    }
    r
    • 2
    • 2
  • k

    Kiprop Victor

    09/25/2021, 10:36 AM
    Hey thought i could share this here: https://twitter.com/MesInc_/status/1441677947048382472?s=20
    🤔 1
    c
    j
    +3
    • 6
    • 14
  • e

    elect

    09/25/2021, 6:07 PM
    how can you create such a DSL with
    +
    and
    -
    operators with implicit receiver?
    branchFilter {
                    +"refs/heads/my-feature"
                }
    c
    t
    • 3
    • 4
  • e

    elect

    09/26/2021, 9:46 AM
    Regarding DSL, is there some way in order to specify some properties as required/exclusive?
    c
    • 2
    • 1
  • h

    Hamza Ahmad

    09/27/2021, 12:09 PM
    Hello everyone, i'm developing application using kmm but my iosApp doesn't run and send back with error that says "Command PhaseScriptExecution failed with a nonzero exit code". And also when I open iosApp in xCode, and moving forward to Buildphases -> Embed Frameworks then xCode-framework is not present in shared/build folder. See Image Below
    a
    • 2
    • 1
  • j

    Jilles Soeters

    09/27/2021, 10:40 PM
    🧵 Hey y’all, I’d like to have some dynamic property access with 2 data classes. I imagine this requires some generics but I am not quite sure how to do this in Kotlin. I have an example here https://gist.github.com/jillesme/d1e1af0e0f56f8b5e02d27f9bc17afa5
    j
    c
    • 3
    • 6
  • v

    Vitali Plagov

    09/28/2021, 10:15 AM
    Hello. I have an
    object
    with constants defined as
    const val
    . I want to get a list of all constants available in this object. Is there a convenient way to get them? I tried with reflection:
    MyObjectWithConstant::class.declaredMemberProperties
    j
    e
    • 3
    • 9
  • e

    elect

    09/28/2021, 11:51 AM
    is there any jvm util (hopefully in kotlin) for dealing/expressing POSIX cron syntax nicely in Kotlin?
    j
    m
    n
    • 4
    • 7
  • y

    Yousef

    09/28/2021, 3:26 PM
    I'm not sure if this is the place to ask and might not be kotlin specific, but if I want a category with a list of subcategories, but I don't want the subcategories to have their own subcategories, how do I do that?
    data class Category(
        val id: UUID,
        var title: String,
        var slug: String,
        var subCategories: List<Category>
    )
    p
    t
    • 3
    • 4
  • v

    Vitali Plagov

    09/28/2021, 5:42 PM
    What would be a
    runCatching
    -equivalent of the
    try {} finally {}
    code in Java? Is it what the
    recover{}
    function does?
    j
    h
    • 3
    • 6
  • d

    Dipendra Singh

    09/28/2021, 8:49 PM
    Hello, Im looking for a way to clean this code. I dont like this part of init empty String, is there other way write this?
    fun getStreetNameByStreetId(id: String): String {
            val query = Query()
            query.fields().include("name")
            query.addCriteria(Criteria.where("_id").`is`(id))
            var streetName = ""
            mongoTemplate.executeQuery(
                query, STREET_COLLECTION
            ) { document: Document ->
                streetName = document.getValue("name").toString()
            }
            return streetName
        }
    j
    m
    • 3
    • 3
  • m

    Manuel Dossinger

    09/29/2021, 7:08 AM
    Is there something like an
    addOrRemove(element, boolean)
    function for sets (or collections) in the stdlib? Something that does
    if (boolean) set.add(element) else set.remove(element)
    🇳🇴 1
    j
    m
    • 3
    • 2
  • e

    elect

    09/29/2021, 8:30 AM
    design question: why when you mark with a
    @DslMarker
    annotation class a method, this gets displayed as yellow? Is this because we want to explicitly show to the user that this is a DSL method?
    c
    a
    • 3
    • 9
  • j

    Javier

    09/29/2021, 8:14 PM
    Someone is getting this issue when trying to disable explicit api?
    kotlin {
      explicitApi = ExplicitApiMode.Disabled
    }
    Error:
    Unknown value for parameter -Xexplicit-api: 'disabled'. Value should be one of {disable, strict, warning}
    The enum class:
    enum class ExplicitApiMode(private val cliOption: String) {
        Strict("strict"),
        Warning("warning"),
        Disabled("disabled"); // this should be renamed to disable and/or in another place have to check for disabled instead of disable
    
        fun toCompilerArg() = "-Xexplicit-api=$cliOption"
    }
    h
    • 2
    • 5
  • w

    William Reed

    09/30/2021, 1:37 PM
    could someone help me understand generics in this situation: This works fine:
    val classes: List<KClass<*>> = listOf(
        Person::class,
        Teacher::class,
    )
    And this produces an error
    val classes: List<KClass<Any>> = listOf(
        Person::class,
        Teacher::class,
    )
    (the difference being
    *
    vs
    Any
    ) I want to store any kclass, and don’t know the types. I thought
    *
    meant they all have the same type but i don’t know what it is
    m
    j
    • 3
    • 7
  • s

    Scott Whitman

    09/30/2021, 1:47 PM
    Is there a cleaner way of doing this? Degrees needs to be immutable, greater than 0, and less than 360.
    class CompassHeading(degrees: Double) {
    
        private var _degrees by Delegates.notNull<Double>()
        var degrees: Double
            get() = _degrees
            set(value) {
                var d = value % 360.0
                if (d < 0.0) d += 360
                _degrees = d
            }
    
        init {
            this.degrees = degrees
        }
    }
    w
    h
    +2
    • 5
    • 9
  • e

    elect

    09/30/2021, 3:32 PM
    Is it legit to have a dedicated interface containing a function with a lambda with a receiver to be implemented by third parts?
    interface Action {
    //    interface DSL Builder
        operator fun<T> invoke(block: T.() -> Unit)
    }
    Because I cant seem to properly override in the implementation..
    r
    • 2
    • 9
  • b

    Byron Woodfork

    09/30/2021, 3:48 PM
    Anyone have some good literature/blog post recommendations for good ways to handle errors in Kotlin and avoid throwing and catching exceptions needlessly?
    h
    a
    +3
    • 6
    • 5
  • j

    Jan

    09/30/2021, 7:45 PM
    Hey! I wrote a kotlin multiplatform library and wanted to test it on the jvm side. But IntelliJ gives me a "Cannot access XY, Check for missing dependencies" error and I can't compile. Its probably something with the publishing because if I add the dependencies manually, it works. I can see the dependecies in "External Libraries" in Intellij Build file from the MP project: https://github.com/jan-tennert/DiscordKM/blob/master/build.gradle.kts Error: (see thread)
    • 1
    • 2
  • j

    Jason5lee

    10/01/2021, 2:11 AM
    I found bitwise-and operator having different behavior in calling via infix syntax and method. Is it expected behavior?
    👍 1
    e
    • 2
    • 3
  • c

    cdpjenkins

    10/01/2021, 10:52 AM
    Is there a function in the Kotlin standard library for that ignores its argument and doesn’t do anything? There have been a few places where I’ve needed to provide a handler to satisfy an API but where I don’t want anything to happen when the handler has been called. I have found myself writing
    fun <T> doNothing(param: T): Unit = Unit
    or an equivalent lambda and I’m wondering if there is a standard function that I can do in order to not have to write this function myself.
    j
    e
    • 3
    • 3
Powered by Linen
Title
c

cdpjenkins

10/01/2021, 10:52 AM
Is there a function in the Kotlin standard library for that ignores its argument and doesn’t do anything? There have been a few places where I’ve needed to provide a handler to satisfy an API but where I don’t want anything to happen when the handler has been called. I have found myself writing
fun <T> doNothing(param: T): Unit = Unit
or an equivalent lambda and I’m wondering if there is a standard function that I can do in order to not have to write this function myself.
j

Joffrey

10/01/2021, 11:05 AM
If you need to pass a function, you can just pass
{ Unit }
. If you need to implement a method (like an override), you can just use
Unit
as your implementation body
c

cdpjenkins

10/01/2021, 11:29 AM
Many thanks. I didn’t realise that it’s possible to do something a simple as`{ Unit }` so that might be enough for me 😺
e

ephemient

10/01/2021, 5:56 PM
even
{ }
should work, although explicitly stating
Unit
is clearer
:thank-you: 1
View count: 5