https://kotlinlang.org logo
Docs
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
  • m

    Marko Novakovic

    04/19/2022, 4:42 PM
    can anyone give me initial direction for web scraping in Kotlin?
    m
    • 2
    • 6
  • o

    Oleg Siboglov

    04/19/2022, 5:41 PM
    Hey all. I was hoping I could get some clarification about the
    inline
    modifier for functions. The Kotlin lang webpage for inline function states “Inlining may cause the generated code to grow. However, if you do it in a reasonable way (avoiding inlining large functions), it will pay off in performance, especially at “megamorphic” call-sites inside loops.” When it states that we should avoid inlining large functions, does this refer solely to the function receiving the
    inline
    modifier or does it apply to the contents of the lambda (which is being passed to the inlined function) as well?
    j
    • 2
    • 2
  • e

    eygraber

    04/19/2022, 9:12 PM
    Is there guidance as to when a property should be inlined (aside from needing reified parameter types)?
    l
    g
    • 3
    • 2
  • c

    Colton Idle

    04/20/2022, 6:37 AM
    I currently have an object that prints out as such
    Country(code=AD, name=Andorra)
    but I need to convert it into json. Is there a stringify method or something I can use from kotlin stdlib in android? Most questions I look up on stackoverflow want me to bring in gson, but I really dont want to bring in a depedency for just this single little manipulation. Am I missing something basic here?
    t
    p
    • 3
    • 5
  • a

    Alex

    04/20/2022, 11:15 AM
    Hi, i am trying to understand more about Ktor and was wondering if there is any dedicated slack channel for asking question related to Ktor, thank you
    👍 1
    r
    m
    • 3
    • 5
  • l

    lucapette

    04/20/2022, 2:58 PM
    hey folks! I’ve been playing around with annotations in this repo https://github.com/lucapette/konfig I’d love someone experienced in writing annotations to have a look at it. I found a bunch a config libraries but liked none of the api. So I thought this was a fun exercise. I’ll provide more context in the thread
    e
    • 2
    • 4
  • m

    Mark

    04/21/2022, 4:21 AM
    Is there a standard lib function that takes an
    Iterable
    and returns true if and only if all items return the same value for a given lambda? I don't care what the value is. I know I can just apply lambda to first item and then use
    Iterable.all {}
    but I was wondering if there was a nicer way.
    m
    m
    e
    • 4
    • 23
  • c

    Cristina Uroz

    04/22/2022, 9:56 AM
    Hi everyone! I’m starting a new project and I was wondering which is the best practice to store an authentication token after a log in to use it in other api calls. Do you have any recommendations?
    a
    j
    • 3
    • 2
  • m

    MR3Y

    04/22/2022, 3:42 PM
    Today, I saw something that is new for me in kotlin's syntax. In https://github.com/zach-klippenstein/compose-fractal-nav, there is an interface
    FractalParent
    that is declared as follows:
    internal interface FractalParent : FractalNavScope {
        // ...
        val zoomAnimationSpecFactory: () -> AnimationSpec<Float>
      // ...
    }
    and the class that implements the interface is:
    internal class FractalNavStateImpl : FractalParent {
        // ...
        override lateinit var zoomAnimationSpecFactory: () -> AnimationSpec<Float>
    my question is how he was able to override
    zoomAnimationSpecFactory
    and change its modifier from
    val
    to
    lateinit var
    without getting a compilation error?
    c
    e
    • 3
    • 4
  • j

    Jan

    04/23/2022, 3:50 PM
    Is there an equivalent to <Class>::new in Kotlin?
    r
    e
    • 3
    • 2
  • a

    Anthony Flores

    04/24/2022, 5:19 PM
    Is it possible to have a function invoked when an instance of a specific class is created in a class? Such as:
    class SomeClass {
        val listOfThing = Array<Thing>()
        val thing1 = Thing()
    
        fun Thing.invoke() {
            listOfThing.add(this)
        }
    }
    r
    p
    • 3
    • 2
  • h

    hooliooo

    04/25/2022, 8:46 AM
    Is it possible to have two instances of the same data class with the same exact properties (and values) be equal but not have the same hashCode? I thought if the two instances are equal then their hashCode should be the same
    r
    b
    • 3
    • 6
  • s

    Stylianos Gakis

    04/25/2022, 1:31 PM
    I have a problem with calling suspending functions from inside a lambda which is provided from an interface. More specifically, the interface has a function that looks like this
    fun foo(lambda: Bar.() -> Unit)
    . On one of the places where I call this, I happen to be inside a suspending function, where I want to be able to simply call on a suspend function like I normally would. This isn’t allowed since that lambda isn’t suspending, and I can’t make it suspending either. I see that this is solved in the vast majority of cases by having the function itself be
    inline
    which makes this possible, however I see that it’s not possible to define an interface function as inline. I’m sure this is something that others have faced as well, what are my options? I see that this is solved by defining them as extension functions to the interface like map is defined, but in my case I can’t do that either since the implementation of my interface wants to use some local variables when implementing this function.
    j
    e
    • 3
    • 7
  • m

    Muhammad Talha

    04/26/2022, 6:18 AM
    Hey all - I'm trying to understand extension functions. I see the value in adding extension methods for other library authors code. However I'm trying to figure out the reason for doing so in your own code. I'm sure there is a reason because I'm seeing it a lot within the Ktor code base. I'm curious since the Ktor devs have access to their own code, why they didn't just add them as regular methods on a class. Would some one be able to shed some light on this? Thank you!
    e
    r
    r
    • 4
    • 6
  • v

    Vitali Plagov

    04/26/2022, 9:31 AM
    I have the following code:
    object TestConfig {
      val ENV_UNDER_TEST by lazy { ... }
    }
    It’s a global variable I’m using in the project that stores the environment name under test. Is it possible to change that variable during the runtime? maybe with reflection or somehow else? I do understand that it’s not supposed to be changed and that it’s a dirty hack, so I accept that risk.
    r
    • 2
    • 1
  • c

    Colton Idle

    04/26/2022, 6:42 PM
    I want to get a list<String> of this enum class.
    enum class BackendEnv(val humanReadableName: String) {
      STAGING("Staging"),
      PROD("Production")
    }
    How would you do it?
    t
    e
    • 3
    • 6
  • a

    Ayfri

    04/26/2022, 8:59 PM
    Hi, how can I set an argument of a data class as having a
    internal set
    ?
    a
    e
    • 3
    • 5
  • g

    Goldcrest

    04/27/2022, 3:32 AM
    Hi, I just ran into this quirky behavior combining if statement as an expression and elvis operator :
    val nonNullVal = 
    if(condition1) { 
        someOperation.get() // null 
    } else if (condition2) { 
        someOperationTwo.get() // null 
    } else { 
        null 
    } ?: defaultVal
    When condition 1 is true our
    nonNullVal
    evaluates to
    null
    . When condition 1 is false and condition 2 is true our
    nonNullVal
    evaluates to
    defaultVal
    What is happening? X_x I would just like to get a grasp of what is going on internally. Any help is appreciated! Thanks!
    j
    e
    • 3
    • 9
  • r

    René

    04/27/2022, 7:08 AM
    I’m extending a java class where I would like to override the getter/setter as properties is that really not possible?
    class Sample<T> {
      @Nullable
      public T getValue() {...}
      protected void setValue(T value) {...}
      //...
    }
    That is the simplified base class I had in mind something like:
    class Foo<T> : Sample<T>() {
      override val `value`: T
        get() {...}
        set(value) {...}
    }
    e
    • 2
    • 6
  • s

    Sam Smallman

    04/27/2022, 9:47 AM
    Currently building a Kotlin library for some NFC logic. How do I import the android.nfc.tech package so that I can use NfcV within the kotlin lib?
    t
    • 2
    • 3
  • r

    René

    04/27/2022, 12:53 PM
    Why does that not compile?
    @set:JvmName("setMyFoo")
    @get:JvmName("getMyFoo")
    open var foo: Int = 42
    without
    open
    it works
    e
    • 2
    • 1
  • r

    rrva

    04/27/2022, 3:59 PM
    Is it possible to set a conditional breakpoint on every String value created in a complex codebase and catch the creation of a specific String? (Regardless of which constructor to java.lang.String is used). I tracked down my specific bug but became curious on how to do it. Or can I get a creation trace via jvm flight recorder?
    k
    • 2
    • 1
  • a

    Anthony Flores

    04/28/2022, 9:45 PM
    How can I use
    is
    with generics? For example if the generic is
    <T : SomeClass>
    how can check if T is a specific child of
    SomeClass
    ?
    j
    m
    • 3
    • 5
  • m

    Mark

    04/29/2022, 1:35 AM
    Please can someone explain why this doesn’t compile:
    interface Sequenceable<out T> {
        fun asSequence(): Sequence<T>
    }
    
    interface Item
    
    interface TypeOfItem: Item
    
    interface Items: Sequenceable<Item>
        
    interface TypeOfItems : Items, Sequenceable<TypeOfItem> // Error message: Type parameter T of 'Sequenceable' has inconsistent values: Item, TypeOfItem
    https://pl.kotl.in/BSez9qCNJ
    e
    t
    • 3
    • 6
  • j

    Jan

    04/29/2022, 2:09 PM
    I have this data class:
    data class AttachmentItem(val imageId: String, val extension: String)
    now I have two lists of these attachments:
    val list1 = listOf<AttachmentItem>()
    val list2 = listOf<AttachmentItem>()
    //now I want to know which AttachmentItems are missing in list1 but are there in list 2 and vice versa. So:
    val diff1 = //attachments available in list1 but not in list2
    val diff2 = //attachments available in list2 but not in list1
    How would I do that in kotlin?
    j
    m
    • 3
    • 3
  • s

    Shumilin Alexandr

    04/29/2022, 8:01 PM
    Hi everyone! please help me, how can i get first 5 elements from from Map<String, Double> ?
    j
    p
    m
    • 4
    • 6
  • s

    Shumilin Alexandr

    04/30/2022, 8:43 PM
    Hi! I have a question! class :
    data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {}
    function:
    fun test(date1: MyDate, date2: MyDate) {
        // this code should compile:
        println(date1 < date2)
    }
    Problem: I need to write a method for comparing MyDate objects I write a solution, it works ok
    override fun compareTo(other: MyDate): Int {
        val yearDiff = year - other.year
        val monthDiff = month - other.month
        val dayDiff = dayOfMonth - other.dayOfMonth
    
        if (yearDiff == 0) {
            if (monthDiff == 0) {
                if (dayDiff == 0) {
                    return 0
                }
            } else return monthDiff
        } else return yearDiff
    
        return 0;
    }
    and now “good” solution:
    override fun compareTo(other: MyDate) = when {
        year != other.year -> year - other.year
        month != other.month -> month - other.month
        else -> dayOfMonth - other.dayOfMonth
    }
    i am not understand how works “good” solution? can you help me? what does mean
    year != other.year -> year - other.year
    c
    e
    +2
    • 5
    • 13
  • t

    Tariyel Islami

    05/01/2022, 7:18 PM
    Hi everybody, Is the logic of the delegate in C# and the delegate in Kotlin the same?
    t
    s
    m
    • 4
    • 6
  • t

    Tianyu Zhu

    05/01/2022, 10:07 PM
    If I run
    myFlow.collect { /* some work */ }
    , is that work being done concurrently? If so, on how many threads? How do I control it?
    m
    j
    • 3
    • 7
  • a

    Alan Lee

    05/03/2022, 6:29 AM
    Anyone see what I am doing wrong here with
    PriorityQueue
    and
    compareBy
    ?
    fun testPQ(words: Array<String>) {
        val heap = PriorityQueue<String>(
            compareBy<String>{ it.length }
        )
    
        words.forEach {
            heap.offer(it)
        }
    
        println(heap)
    }
    
    fun main() {
        val input = arrayOf("the","day","is","sunny","tha","a","def","sunny","as","by")
        testPQ(input)
    }
    The result I see is
    [a, as, is, day, by, the, def, sunny, sunny, tha]
    by
    and
    tha
    seems to be out of order.
    e
    • 2
    • 3
Powered by Linen
Title
a

Alan Lee

05/03/2022, 6:29 AM
Anyone see what I am doing wrong here with
PriorityQueue
and
compareBy
?
fun testPQ(words: Array<String>) {
    val heap = PriorityQueue<String>(
        compareBy<String>{ it.length }
    )

    words.forEach {
        heap.offer(it)
    }

    println(heap)
}

fun main() {
    val input = arrayOf("the","day","is","sunny","tha","a","def","sunny","as","by")
    testPQ(input)
}
The result I see is
[a, as, is, day, by, the, def, sunny, sunny, tha]
by
and
tha
seems to be out of order.
e

ephemient

05/03/2022, 6:41 AM
the head of a priority queue is the least element, but no guarantees are made about the iteration order of the rest of the pq. you can only determine the second-least by removing the first element
👍 1
your choice of "heap" as the variable name there is telling - look up how a binary heap is implemented
a

Alan Lee

05/03/2022, 7:35 AM
Of course. What was I thinking. Thanks for pointing that out. I’m not sure why I thought that it should be sorted.
View count: 4