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

    Slackbot

    09/17/2022, 10:19 AM
    This message was deleted.
  • e

    Ellen Spertus

    09/18/2022, 1:47 AM
    Is there a name for classes that aren't enum classes or data classes, or are they just plain old classes?
    c
    l
    • 3
    • 2
  • e

    Eric Womer

    09/18/2022, 2:34 PM
    Are there any api docs for kotlin/compose that are easily searchable and not spread around 40 or so different web pages?
    g
    • 2
    • 3
  • r

    rrva

    09/18/2022, 5:29 PM
    if i have a singleton declared with object syntax
    object Foo { ... }
    why is it still possible to read an instance of this "class" using jackson objectMapper with
    objectMapper.readValue(input, Foo::class.java)
    and then I can access fields from that.. Does this not violate the singleton?
    e
    • 2
    • 2
  • h

    homchom

    09/18/2022, 9:43 PM
    I'm having trouble passing a method reference into a Kotlin function. What's weird is it works if I declare and pass it from Kotlin, but if I declare/pass from Java I get a compile error. The type resolves correctly in the first line, but it complains in the second line, even though the type I'm passing looks like it should meet all variance requirements. I verified that all imports are correct, and, again, it works in an equivalent Kotlin file. Any ideas? (Note that the type
    Pair<List<String>, String>
    is just for testing purposes and is not final.)
    e
    • 2
    • 7
  • m

    Midoriya

    09/19/2022, 4:45 AM
    i have list of TodoItem
    data class TodoItem(
        val taskName :String,
        val isCompleted : Boolean  = false,
    )
    
     private val taskList = mutableListOf<TodoItem>()
    how can i change an element 'isCompleted' to true. so if user said 4th element is completed how can i change it to complete
    taskList[index] = TodoItem(taskName = taskList[index].taskName, isCompleted = true)
    like this???
    e
    • 2
    • 2
  • c

    cpe

    09/19/2022, 8:05 AM
    Hi all, this topic is more advanced but I can’t find a better channel to place it. I need to execute some code on startup without knowing of its existence, think of an expendable registry where classes can register themselves (somehow like observer). The challenge is that - as I can’t instantiate these classes (actively) - the code is currently within a
    companion object
    . So I decided to provide an interface (or an annotation) and find the functions to call on startup as follows using (using classgraph as for scanning - I’m not bound to that framework):
    interface OnStartup {
      fun onStartup()
    }
    
    // a class that wil instantiated a lot of times during runtime
    data class SomeClass(val name: String) {
      companion object : OnStartup {
        override fun onStartup() {
          // notify someone at startup about our existence
        }
      }
    }
    
    fun main() {
      ClassGraph().enableAllInfo().acceptPackages("com.test").scan()
        .getClassesImplementing(OnStartup::class.java)
        .filter { it.isStatic }
        .flatMap { findStartupMethods(it) }
        .forEach {
          it.call()
        }
    }
    
    private fun findStartupMethods(classInfo: ClassInfo): List<KFunction<*>> {
      return classInfo.methodInfo.filter { function ->
        function.name == "onStartup"
      }.mapNotNull { method ->
        method.loadClassAndGetMethod().kotlinFunction
      }
    }
    This will not work as
    call()
    expects a parameter:
    Callable expects 1 arguments, but 0 were provided.
    which should be the instance of the class (from my understanding), so I guess it should be the
    companionObjectReference
    . The code works well if I define the
    onStartup
    function on top level (but that has negative impacts for my idea). Is there any way to retrieve the
    companionObjectReference
    ? Or to achieve this behaviour? Maybe there is another annotation scanner that fits better for Kotlin? Any help is appreciated.
    y
    • 2
    • 2
  • m

    Michael de Kaste

    09/19/2022, 8:27 AM
    Maybe I'm just blind, but given that there is a
    .single()
    , I would expect there to be function that does this: • If there are no elements: null • If there is one element: it • If there are more elements: exception However, the implementation
    .singleOrNull()
    returns null on multiple elements too. There have been several occassions where we now check size first and manually do a 0,1,else check to do this correctly, but am I just missing something or should I just do a language proposal?
    j
    • 2
    • 2
  • c

    Christoph Frädrich

    09/19/2022, 9:55 AM
    Hi everyone, is this the right place to ask questions regarding ktor and kotlinx? I am looking for info on how to add ids (like you would in html) to elements created with kotlinx.html, for example adding an id to a list item, so I find the list item in a javascript function.
    c
    • 2
    • 2
  • e

    Erik

    09/19/2022, 10:02 AM
    I'm looking for some idiomatic Kotlin to replace an element in a
    List<T>
    at some index, i.e. I'd create a new list. Currently I do:
    val list: List<T> = /*..*/
    val elementToReplace: T = /*...*/
    val newElement: T = /*..*/
    val newList = list.toMutableList().apply {
        this[indexOf(elementToReplace)] = newElement
    }
    E.g. as an extension:
    fun <T> List<T>.replaceWith(old: T, new: T): List<T> = toMutableList().apply {
        this[indexOf(old)] = new
    }
    Can this be done with some stdlib function, or in a shorter more idiomatic way?
    e
    y
    • 3
    • 15
  • g

    Gasan

    09/19/2022, 11:52 AM
    hi here, I am having a companion object, that declares a method annotated with
    JvmStatic
    I want to write a junit/mockito test where I want to mock the method. Is there a way to do it? What if I remove
    JvmStatic
    ? What are my options? I think it’s a part of the broader topic - how does the companion object relate to beans/singleton concepts of
    Spring
    , for example. Ideally, I would want no static methods at all. But instead having a singleton-y classes that I could mock or do whatever I can with the normal classes.
    e
    • 2
    • 15
  • c

    CLOVIS

    09/19/2022, 12:02 PM
    abstract class A {
        abstract inner class B : A() {
            init {
                // How can I access the outer class?
            }
        }
    }
    In that example,
    this
    refers to the class
    B
    ,
    this@A
    refers to the parent class. How can I access the outer class?
    m
    v
    r
    • 4
    • 10
  • j

    Jérémy CROS

    09/19/2022, 3:29 PM
    Just noticed something today:
    fun smartCast(
        condition1: String?,
        condition2: String?
    ): String? {
        if (condition1 == null || condition2 == null) return null
        return dummy(condition1) // OK, smart cast succeed
    }
    
    fun smartCastFailed(
        condition1: String?,
        condition2: String?
    ): String? {
        val checkCondition = condition1 == null || condition2 == null
        if (checkCondition) return null
        return dummy(condition1) // KO, smart cast fails
    }
    
    fun dummy(condition: String): String = TODO("do something with condition")
    That might seem like a stupid example but I had a bunch of conditions that would not fit in one line and I also wanted to explicit a bit the check with the variable. I assume this type of optimization is a bit hard for the compiler? Any way around that? I guess using
    !!
    is fine since I’m sure the condition is not null.
    d
    • 2
    • 2
  • g

    Gasan

    09/19/2022, 8:06 PM
    Hi here, what is the use case for the companion objects? Coming from the java world, the normal way (to me ) would be to instantiate a singleton (using a container) and then provide it as a dependency to the caller code. Companion objects seem to work as a hardcoded dependencies, essentially not different from the static method calls.
    c
    t
    • 3
    • 17
  • g

    Gasan

    09/20/2022, 7:40 AM
    Hi here, I was reading this answer: https://discuss.kotlinlang.org/t/best-practices-for-top-level-declarations/2198/3 on kotlin forum. The author references “recommended practice” what practices is he talking about and where can I find them?
    a
    m
    • 3
    • 3
  • r

    reactormonk

    09/20/2022, 9:47 AM
    The API is android, but the question itself isn't, feels more like a basic Kotlin question. I have this API to implement: https://developer.android.com/reference/androidx/activity/result/contract/ActivityResultContract by inheritance. The
    parseResult
    demands a non-null return value - however,
    null
    is a possible result I may get in there. How do I wrap the
    null
    into a non-null value, so the compiler is happy with me?
    j
    r
    +2
    • 5
    • 9
  • g

    Gleb Minaev

    09/20/2022, 11:50 AM
    Can anyone show me place in Kotlin docs (or maybe even in Kotlin spec) where full description of deferred assignment usage rules is placed? All I found about deferred assignment is short mention in "Basic syntax" page. But obviously the rules are not trivial...
    j
    e
    +2
    • 5
    • 8
  • a

    abu naser

    09/21/2022, 11:52 AM
    here i tried to reproduce my problem .. for set of custom data filter and then remove is not working but remove if is working fine.. and if any inner value not change then its works ..
    import org.junit.Test
    
    class TestMutableSetDelete {
        @Test
        fun testRemoveMutableSet(){
            val data = TestSetList(mutableSetOf(), mutableSetOf())
            add(data)
            change(data)
            //deletes not work in any inner value ever change 
            delete(data)
            // removeIf always works . but i my code need to work below api 24 too.
    //        data.span.removeIf { it.start==it.end }
            // FIXME: without change this works . but if change happend its not
            data.range.forEach { println("start > ${it.start} > ${it.end}") }
            assert(data.range.size==2)
        }
    }
    data class TestSetList(
        val range: MutableSet<Range> = mutableSetOf(),
        val para: MutableSet<Para> = mutableSetOf()
    )
    data class Para(
        val start:Int,
        val end:Int
    )
    data class ChangedData(
        var name:String="",
        var age:Long
    )
    data class Range(
        val start:Int,
        val end:Int,
        val changedData: ChangedData
    )
    fun add(data:TestSetList){
        val cd =ChangedData("naser",26)
        data.range.add(Range(0,0,cd))
        data.range.add(Range(1,2,cd))
        data.range.add(Range(1,5,cd))
        data.range.add(Range(2,2,cd))
        data.range.add(Range(3,3,cd))
    }
    fun change(data: TestSetList){
        //simulate some change in the process .
        data.range.forEach { it.changedData.name = it.start.toString() }
    }
    fun delete(data:TestSetList){
        data.range.filter { it.start == it.end }.forEach { data.range.remove(it) }
    }
    i
    m
    • 3
    • 8
  • m

    mattinger

    09/21/2022, 1:27 PM
    So, after upgrading to kotlin 1.7.10, the exhaustive when clause has kicked in. This has caused us to have to add a lot of this type of block to our code in cases where we’re only interested in one or two cases of an enum:
    SOME_VALUE_WE_DONT_CARE_ABOUT -> { }
    The issue is that sonarqube is treating this as a code smell, and our quality gate is blocking merges when this happens. So we have to either change our quality gate, or use admin privs to merge. Does anyone know if there’s a way to tell sonar to ignore these?
    k
    k
    +2
    • 5
    • 6
  • g

    Gasan

    09/21/2022, 1:51 PM
    hi here, what are good books on writing idiomatic kotlin? Or maybe ones that teach general programming using kotlin.
    s
    g
    • 3
    • 2
  • m

    Márk Bartos

    09/22/2022, 8:52 AM
    hey. where can i read how does this works: ?
    kotlin
    InputDecoration(color=if(isValid) blue else red) {
        Input(value, onChange)
      }
    r
    j
    b
    • 4
    • 8
  • j

    Joshua Hansen

    09/24/2022, 5:45 AM
    Looking for a way to make this code more kotlin-like. Just trying to get more comfortable with the more nuanced syntactical aspects of the language. My code is like this:
    val foo: Map<String, String> = if (str.contains(bar1)) {
        map1
    } else if (str.contains(bar2)) {
        map2
    } else if (str.contains(bar3)) {
        map3
    } else {
        defaultMap
    }
    The maps are properties defined in the class that this function is in. There is potential for more maps to be added in the future. This is basically a way for me to select which map to use.
    str
    is a value passed into this function and is expected to meet 1 of the 3 criteria. Is there a more clever way to do this?
    t
    e
    • 3
    • 5
  • z

    zt

    09/25/2022, 5:09 AM
    Python has a
    random.choices()
    method which lets you provide a list of options and a list of weights for them. Is there some equivalent way to do that in kotlin?
    e
    • 2
    • 1
  • d

    D Tam

    09/25/2022, 12:05 PM
    Apologies if this question has been asked before. How do you verify that Google's advertising id is legitimate i.e. they recognise that they id exists in their system.
    y
    • 2
    • 1
  • y

    Yusuf.I

    09/25/2022, 7:12 PM
    is it possible to do something like this in kotlin
    interface ClientEvents {
      ready: () => void;
    }
    
    export declare interface Client {
    
      on<Event extends keyof ClientEvents>(
        event: Event,
        listener: ClientEvents[Event],
      ): this;
      off<Event extends keyof ClientEvents>(
        event: Event,
        listener: ClientEvents[Event]
      ): this;
      emit<Event extends keyof ClientEvents>(
        event: Event,
        ...args: Parameters<ClientEvents[Event]>
      ): boolean;
    }
    a
    • 2
    • 26
  • e

    Ellen Spertus

    09/25/2022, 11:06 PM
    I'm reading the Kotlin
    String
    API and have a few questions... https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/
    f
    g
    • 3
    • 6
  • z

    zt

    09/26/2022, 2:32 AM
    How could I use markov chains to generate a string? I couldn't find any kotlin examples
    s
    • 2
    • 1
  • c

    CLOVIS

    09/26/2022, 8:53 AM
    null
    is a valid value for
    out Any?
    , right?
  • c

    CLOVIS

    09/26/2022, 9:18 AM
    It seems like it should be allowed, yet this fails to compile:
    interface Param
    
    data class A<P : Param?>(val v: (P) -> Unit)
    
    fun <P> create(v: (P) -> Unit) = A(v)
    
    fun main() {
        val a = create { _: Nothing? -> }
    
        println(a.v(null)) // Null can not be a value of a non-null type Nothing
    }
    According to IDEA,
    a
    has type
    A<out Any?>
    , so why is
    null
    not allowed? (playground link)
    s
    r
    j
    • 4
    • 7
  • m

    martmists

    09/26/2022, 6:12 PM
    Does kotlin have something similar to
    \xFF
    escapes in strings? I can only find
    \uFFFF
    but this will likely create two bytes instead of one
    e
    • 2
    • 7
Powered by Linen
Title
m

martmists

09/26/2022, 6:12 PM
Does kotlin have something similar to
\xFF
escapes in strings? I can only find
\uFFFF
but this will likely create two bytes instead of one
e

ephemient

09/26/2022, 6:13 PM
like Java,
Char
is a 16-bit value
m

martmists

09/26/2022, 6:21 PM
Then what's the recommended way to create a UByteArray from a string? I currently have
fun String.toUByteArray(): UByteArray {
    val chunks = chunked(2)
    val result = UByteArray(length) {
        chunks[it].toUByte(16)
    }
    return result
}
but ideally I could just use escapes so I could do
"somedata\x01\x02\x03"
instead of having to write everything as hex
e

ephemient

09/26/2022, 6:24 PM
on JVM, you could
"somedata\u0001\u0002\u0003".toByteArray(Charsets.ISO_8859_1).asUByteArray()
and on multiplatform, you could
"somedata\u0001\u0002\u0003".map { it.code.toUByte() }.toUByteArray()
but there isn't really a good ergonomic way to do this
or
UByteArray(string.length) { string[it].code.toUByte() }
to skip the intermediate
List
m

martmists

09/26/2022, 6:29 PM
so there's no shorthand for 1-byte characters like \xFF?
e

ephemient

09/26/2022, 6:33 PM
there are no one-byte characters
even
'a'
is a UTF-16 code unit
View count: 7