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

    Tolriq

    06/03/2022, 2:53 PM
    Is there a way to access a parent of a parent field via kotlin reflection without relying on kotlin reflect?
    javaClass.superclass.
    works for the 1st level parent but
    javaClass.superclass.javaClass.superclass.
    Does not for the second one 😞
    r
    • 2
    • 2
  • j

    Jonathan Ellis

    06/03/2022, 3:14 PM
    operator fun Body.iterator(): Iterator<Body> {
        val body = this
        return object : Iterator<Body> {
            var current: Body? = body
    
            override fun hasNext(): Boolean {
                return current != null
            }
    
            override fun next(): Body {
                val result = current!!
                current = result.getNext()
                return result
            }
        }
    }
    c
    m
    +2
    • 5
    • 12
  • j

    Jonathan Ellis

    06/03/2022, 3:15 PM
    I tried
    var current: Body? = this@Body
    but the compiler doesn't like that
    :thread-please: 2
    j
    c
    y
    • 4
    • 8
  • n

    Nat Strangerweather

    06/03/2022, 5:24 PM
    I'm trying to to get 28 letters from an array of 90. The array of 90 needs to be shuffled so that the set of 28 letters is virtually never the same. So this is the code I use:
    private fun shakeLetterBag(slice: IntRange): Array<Letter> {
            repository.arr.shuffle()
            return repository.arr.sliceArray(slice)
        }
    
        var boardLetters = MutableLiveData(repository.arr)
    
        fun loadTiles(): Array<Letter>? {
            boardLetters.value = shakeLetterBag(0..27)
            return boardLetters.value}
    I am wondering if there is something wrong with my logic because I seem to be getting the occasional identical set, which statistically should not be the case. Any ideas? 🤔
    r
    e
    +2
    • 5
    • 33
  • j

    Jonathan Ellis

    06/03/2022, 5:28 PM
    When is .forEach {} preferred, vs java-style for loop? It looks like both get support from the language, e.g. destructuring for loop values
    f
    r
    +2
    • 5
    • 8
  • j

    Jan

    06/05/2022, 12:34 PM
    Is it right that this prints "1"?:
    val tags = "".split(" ")
    println(tags.size) //prints 1
    :yes: 12
    j
    • 2
    • 1
  • l

    Lawrence

    06/06/2022, 7:43 PM
    is it possible to ignore new lines in a multiline string? In Java, one can use
    \
    to do so. Wondering if Kotlin has something similar
    String a = "This is a long string";
    String b = """
         This is a \
         long string""";
    a.equals(b) // true
    j
    n
    • 3
    • 4
  • e

    elect

    06/07/2022, 11:14 AM
    isn't possible to specify type variable on function references, is it?
    y
    e
    • 3
    • 3
  • i

    Iwan Aucamp

    06/07/2022, 11:46 AM
    should I use ktfmt or ktlint?
    j
    • 2
    • 1
  • w

    Wojciech Rozwadowski

    06/07/2022, 1:43 PM
    How to create extension function for class implements
    invoke
    operator? I tried to do this with below function:
    operator fun <Param, T : Any> ((Param) -> T).invoke(
        param: Param,
        onResult: (Result<T>) -> Unit
    ) {
        val state = runCatching { this@invoke(param) }
        onResult(state)
    }
    Above works fine for this function reference:
    fun test(param: Int): String = "testFunction"
    and lambda itself but not for this class:
    class ClassTest {
        operator fun invoke(param: Int): String = "testClass"
    }
    Any suggestions?
    fun main() {
        val testLambda = { param: Int -> "testLambda" }
        val testFunctionReference = ::test
        val testClass = ClassTest()
    
        testLambda(1) // returns String
        testLambda(1) { onResult: Result<String> ->
            // do sth
        }
    
        testFunctionReference(1) // returns String
        testFunctionReference(1) { onResult: Result<String> ->
            // do sth
        }
    
        testClass(1) // returns String
        testClass(1) { onResult: Result<String> ->
            // Too many arguments for public final operator fun invoke(param: Int): String defined in ClassTest
        }
    }
    r
    • 2
    • 2
  • j

    Jonathan Ellis

    06/07/2022, 2:48 PM
    Is there a way to ask youtrack to show me issues that I voted for?
    :not-kotlin: 1
    p
    • 2
    • 3
  • s

    Scott Peterson

    06/07/2022, 3:47 PM
    Let me know if there’s a better channel to post this in: I’ve got a
    UInt8
    encoded byte array that I need to convert to a UTF-8 string, using Kotlin. various things I’ve tried have converted it into the ASCII value “d”, which is the correct value. But I want the UTF-8 string value “100"
    j
    e
    • 3
    • 8
  • j

    Jonathan Ellis

    06/07/2022, 7:49 PM
    are any of the hard-copy kotlin books worth buying and reasonably up-to-date?
    👀 1
    a
    • 2
    • 1
  • j

    Jonathon Cain

    06/07/2022, 8:32 PM
    Hey ya'll, I was wondering if there might be a list of feature requests for Kotlin out there. Especially if that list has some data tied to it like the amount of user demand, where the feature might eventually live and be maintained, if anyone is actively working on it, etc... I'm aware of the Jetbrains Youtrack, but I haven't used it before. If my answer is there and I just need to learn how to look, I'm happy to learn. My goal is to get a bit more more experience with various aspects of Kotlin so I can get creative when I need to on a future KMM project I intend to start in a few months. This just seemed like a good way to immerse myself to that end. Anyway, thanks for the guidance upfront, and I hope my question didn't come off as daft.
    o
    p
    • 3
    • 4
  • d

    Dragos Rachieru

    06/08/2022, 9:08 AM
    Hello, is there a method to calculate a value between a range? Like if I want to get a value that is
    X
    or
    min
    or
    max
    , like:
    X=50
    ,
    min=0
    ,
    max=40
    , then the result is
    40
    I need this to calculate some positions, don't know if there's a method using
    IntRange
    r
    s
    • 3
    • 5
  • a

    allan.conda

    06/08/2022, 10:13 AM
    Wrapping with
    let
    hides the uninitialized variable being null. Is there an explanation regarding this? Seems Kotlin (1.6.21) is not null-safe in this situation.
    class SomeClass { // extremely minified code
    
      val foo = let { bar } // compile error (almost broke production but my unit test captured it)
      // val foo = bar // compile error (safe!)
        
      val bar = true
    }
    e
    k
    r
    • 4
    • 7
  • k

    kevin_abrioux

    06/08/2022, 11:25 AM
    Hi, how can I invite someone on this slack?
    👀 1
    j
    • 2
    • 3
  • j

    Jonathan Ellis

    06/08/2022, 7:54 PM
    is it impossible to use -- and ++ operators with a nullable Int ?
    e
    r
    a
    • 4
    • 10
  • j

    james

    06/09/2022, 1:09 AM
    for those who are using Kotlin in large, multi-module production codebases, what tooling are you using for Kotlin specific code coverage? we have historically used JaCoCo which served us well for many years, but our codebase is now >50% Kotlin and we’ve found that JaCoCo’s update cycle moves a little too slow for the frequency with which we update to the latest stable versions of Kotlin.. so when we bump our Kotlin version we end up seeing dramatic coverage drops when the newer Kotlin compiler adds extra branches etc to bytecode for existing code, since JaCoCo doesn’t know how to handle/filter these branches yet I’ve heard conflicting reports of how well JetBrains’ own kotlinx.kover library works (fair enough, since it is a relatively new tool) so I am exploring that, but I would love to hear what others are using for Kotlin coverage
    t
    • 2
    • 1
  • t

    thanksforallthefish

    06/09/2022, 5:44 AM
    very dumb question, why does idea complain about unsafe cast in
    fun cast(value: Any?) = (value as? Map<String, String?>)
    ? maybe followup question, am I misusing
    as?
    ? context, in this scenario I know that
    value
    might not be a map, so using
    as?
    on purpose since it returns
    null
    , but this “null-trick” makes the cast safe in my eyes, since `null`s need to be handled explicitly
    j
    • 2
    • 2
  • j

    Jonathan Ellis

    06/09/2022, 8:31 PM
    Does idiomatic Kotlin use classes to organize code or is that a relic of my Java background? Specifically, is it good form to group related stateless functions in a class's companion object, or is it better to use a sub-package?
    l
    l
    • 3
    • 3
  • m

    Mark

    06/10/2022, 5:10 AM
    Why does this extension function not call
    SpannableStringBuilder.inSpans()
    fun <A : Appendable> A.inSpans(vararg spans: Any, builderAction: A.() -> Unit): A =
        if (this is SpannableStringBuilder) {
           // PROBLEM: doesn't call SpannableStringBuilder.inSpans()
           inSpans(spans = spans, builderAction = builderAction) 
        } else {
            builderAction()
            this
        }
    e
    • 2
    • 14
  • z

    zain

    06/10/2022, 12:21 PM
    How to convert Hexcode to String with Emoji? Input HexCode o/p D83EDD2A0024D83DDC3900700072006F0061007300610073006C006D006B0073006B0033002326BDFE0F
    p
    • 2
    • 2
  • g

    gabin

    06/10/2022, 3:34 PM
    Can I inherit data class?
    p
    • 2
    • 1
  • l

    Lawrence

    06/10/2022, 6:35 PM
    I have got two APIs A and B such that only one maybe active at a time but not both. I wanted to determine which type I am connected to by making two parallel calls to their respective APIs and select the first successful one. I tried using select expression with a timeout of 15 seconds. Is this a good way to achieve such a thing?
    // The api I am working with is blocking and throws an error if not connected 
            suspend fun determineType(): Type?  {
                var type: Type? = null
                withTimeoutOrNull(15.seconds) {
                    while (type == null) {
                        select<Unit> {
                            async {
                                runInterruptible(<http://Dispatchers.IO|Dispatchers.IO>) {
                                    kotlin.runCatching { apiA.typeA }.getOrNull()
                                }
                            }.onAwait {
                                if (it != null) {
                                    make = it
                                }
                            }
                            async {
                                runInterruptible(<http://Dispatchers.IO|Dispatchers.IO>) {
                                    kotlin.runCatching { apiB.typeB }.getOrNull()
                                }
                            }.onAwait {
                                if (it != null) {
                                    type = it
                                }
                            }
                        }
                    }
                }
                return type
            }
    m
    p
    +2
    • 5
    • 6
  • w

    wck

    06/11/2022, 1:54 AM
    Hi guys, has something changed in 1.6.21 regarding nullables? code posted in thread.
    e
    • 2
    • 10
  • s

    smit01

    06/11/2022, 8:58 AM
    Can someone give a simple code example of builder inference in new kotlin 1.7.0 version. I tried to go through docs but didn't quite understand please.😅
    e
    • 2
    • 2
  • n

    Nat Strangerweather

    06/11/2022, 7:13 PM
    Hi, I have a list of Booleans, and I need to know the index of all the ones that are false, so a list of indexes. What is the best way to achieve this?
    e
    s
    +3
    • 6
    • 16
  • e

    Elizeu Silva dos Santos

    06/12/2022, 6:34 PM
    do we have any alternative to flyway written in Kotlin?
    r
    • 2
    • 2
  • e

    elect

    06/13/2022, 7:49 AM
    I have a two-level hierarchy with a root and one or more children. Each of these children have a list of elements they need to track, and I'd like also to have somehow a "root" list in the root that incorporates all the children lists. Is there a (easy/stdlib) way to have just the root list and then each child simply manages a subset/view of this list (removing/adding)? Ps: no synch problems, everything is serial
    e
    m
    n
    • 4
    • 12
Powered by Linen
Title
e

elect

06/13/2022, 7:49 AM
I have a two-level hierarchy with a root and one or more children. Each of these children have a list of elements they need to track, and I'd like also to have somehow a "root" list in the root that incorporates all the children lists. Is there a (easy/stdlib) way to have just the root list and then each child simply manages a subset/view of this list (removing/adding)? Ps: no synch problems, everything is serial
something in the direction of `subList`(here) but I guess if the root or the first child modifies the list, then I have to update indices for all the other children..
e

ephemient

06/13/2022, 7:52 AM
if the children are immutable, sure. if they are mutable you will have to define your requirements more specifically
val child = object : AbstractCollection() {
    override val size get() = root.count { isChild }
    override fun iterator() = root.filter { isChild }.iterator()
}
e

elect

06/13/2022, 7:59 AM
each child has a consequential view on the (root) list, ie the first [0-10], the secon [11-40], etc
m

Michael de Kaste

06/13/2022, 10:16 AM
I had the same issue when I had some sealed class which was viewed by the root and the implementations managed by its children. depending on your usage combination: • root view, child view • root view, child mutate • root mutate, child mutate • root mutate, child view there are different solutions. if you have root view and child mutate, you can simply have root be a value that on every request returns a new list based on the children. You can make it better by defining your own concatenation iterator
e

elect

06/13/2022, 10:18 AM
i have the worst I guess, root mutate, child mutate
m

Michael de Kaste

06/13/2022, 10:27 AM
what needs to happen when root adds? Just add it to the final sublist?
e

elect

06/13/2022, 12:04 PM
yep
atm I'm leaning toward a
map<name, ArrayList>
on the root containing the corresponding children lists and then forwarding the methods I need
e

ephemient

06/13/2022, 12:08 PM
if the root exposes a MutableList, you'll have to figure out what to do with insertions and removals at any index and before or after any listiterator
if it's a MutableCollection, then you "only" have to figure out what to with removals before any mutableiterator and additions to the whole collection
n

nkiesel

06/13/2022, 7:01 PM
do I understand correctly that each child is defined as an index range of the root list? Thus, a list of items and a list (or map if children are not identified by index) of IntRange would do the trick?
View count: 5