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

    Lukas K-G

    11/16/2022, 8:56 PM
    Hi 👋 Quick question: When developing a library (in my case an Android library), how do I know with which other Kotlin versions it will be compatible? E.g. when I am using latest 1.7, will a consumer of my library that uses Kotlin 1.5 have issues?
    c
    l
    +2
    • 5
    • 16
  • y

    Yogeshvu

    11/17/2022, 12:16 AM
    are there any good encryption/decryption libraries in kotlin/JVM for storing license file information(perhaps specific to a given hardware/platform)?
  • x

    Xad Kile

    11/17/2022, 3:35 AM
    is there something like
    val myVar by lazy{ something() }
    , but does not cache the value, but re-evaluates the value every time
    myVar
    it is access?
    myVar
    is a local variable
    e
    g
    • 3
    • 17
  • y

    y

    11/17/2022, 7:17 AM
    I want a
    sealed class
    where children share some common variables. how do I do this with the least amount of boilerplate? what I was recommended is something like
    sealed class Parent {
        abstract val s: String
    
        data class Derived1(override val s: String, ...) : Parent()
        data class Derived2(override val s: String, ...) : Parent()
        
        sealed class Derived3() : Parent() {
            data class Derived4(override val s: String, ...) : Derived3()
        }
    }
    which repeats the
    val s
    declaration
    g
    e
    s
    • 4
    • 27
  • r

    Rob Elliot

    11/17/2022, 2:26 PM
    There's no trivial way to make a
    value class
    expose all its value's members at the top level is there?
    s
    p
    y
    • 4
    • 7
  • j

    Justin Tullgren

    11/17/2022, 5:37 PM
    Hi, is it a problem to have a package contain the word internal? ex:
    com.company.internal.feature
    ?
    c
    y
    e
    • 4
    • 4
  • l

    LIRAN Y

    11/17/2022, 7:25 PM
    Hi 🙂
    import com.fasterxml.jackson.annotation.JsonProperty
    import com.fasterxml.jackson.module.kotlin.readValue
    
    data class InsideList(
        @JsonProperty("price") val price: String,
        @JsonProperty("product") val product: String
    )
    
    data class NList(
        @JsonProperty("listexample") val listexample: List<InsideList>?
    )
    the
    response
    is the json list
    val jsonResponse = MapperUtility.jsonMapper.readValue<NList>(response)
    
    println("Response : {${jsonResponse.listexample}}")
    the print is:
    NList(listexample=[InsideList(product=apple, price=ten)])
    how can i print just the value of the product? i tried to do it with
    forEach
    but not works as expected 🙄
    r
    • 2
    • 2
  • l

    Lukasz Kalnik

    11/18/2022, 10:21 AM
    Whenever I refactor Kotlin code in Android Studio and I get an automatic suggestion to rename some class properties, the suggested names all start with
    m
    in the old Java naming convention:
    mSomeProperty
    . Can I configure it somewhere that Kotlin refactoring doesn't use (obsolete) Java naming conventions?
    s
    • 2
    • 3
  • j

    Joshua Hansen

    11/18/2022, 2:53 PM
    Conceptual question here. I have a class which contains a list. Whenever the size of the list is 1, I want certain functions to be used, and when it's greater than 1, I want alternative functions (which serve the same purpose but do something a bit different) to be used. (it's a Java swing app in kotlin so lots of gui stuff). What sort of structure should I use to keep this organized?
    c
    e
    +2
    • 5
    • 6
  • a

    Ayfri

    11/18/2022, 11:06 PM
    Why I can't access a method whose receiver is Test inside the class Test2 when inside a builder with Test ? But I can adding
    with
    of my instance of Test2.
    class Test(var name: String = "test")
    
    class Test2 {
        fun Test.method() = name
    }
    
    fun builder(block: Test.() -> Unit) = Test().apply(block)
    
    fun main() {
        val a = Test2()
        
        builder {
            with(a) {
                println(method()) // can access method()
            }
            println(a.method()) // cannot access a.method() for some reason ?
        }
    }
    c
    l
    • 3
    • 5
  • g

    Georg Ekeberg

    11/19/2022, 2:54 PM
    How do you type maps properly in Kotlin? I want to make a type that is a map with two required keys. tried using class, but I am at a loss.
    abstract class GameState(i: Int, i1: Int) {
        abstract val pinsLeft: Int
        abstract val triesLeft: Int
    }
    
    fun roll(pinsDown: Int,
             pinsLeft: Int = 10,
             triesLeft: Int = 2): GameState {
        return mapOf(Pair("pinsLeft", pinsLeft - pinsDown), Pair("triesLeft", --triesLeft)
    }
  • g

    Georg Ekeberg

    11/19/2022, 2:56 PM
    The problem is that the typing system doesnt know if a key gives back a value in my map (which I use to store my state):
    @Test
    fun `Roll returns how many pins are left when rolling 0 twice`() {
        val state = roll(0)
        assertEquals(0, roll(state["pinsLeft"], state["triesLeft"])
    }
  • g

    Georg Ekeberg

    11/19/2022, 2:57 PM
    Is this climbing uphill with Kotlin? Should I just create my own datastructure GameState with getters, constructors and setters? Or is there a good way to do this with the inbuilt map structure?
    s
    • 2
    • 6
  • g

    Georg Ekeberg

    11/19/2022, 3:04 PM
    Is this a viable approach?
    data class GameState(val i: Int, val i1: Int) {
        private val pinsLeft = i
        private val triesLeft = i1
    
        operator fun get(s: String): Int {
            when (s) {
                "pinsLeft" -> return pinsLeft
                "triesLeft" -> return triesLeft
            }
        }
    }
    j
    s
    • 3
    • 5
  • x

    xun su

    11/20/2022, 1:15 AM
    Hi, does someone knows how to defined a function of any type in kotlin ? no matter what the param and return are . In typescript, we can do it like this:
    type Fn = (...args:any[]) -> any
    but I don't know how to do it in Kotlin.
    j
    h
    r
    • 4
    • 14
  • g

    Gordon

    11/20/2022, 12:34 PM
    I'm looking at the Icons declaration in compose, an i have a style question. Right now the icons declaration looks like this:
    public val Icons.Filled.Circle: ImageVector
        get() {
            if (_circle != null) {
                return _circle!!
            }
            _circle = materialIcon(name = "Filled.Circle") {
                materialPath {
                    moveTo(12.0f, 2.0f)
                    curveTo(6.47f, 2.0f, 2.0f, 6.47f, 2.0f, 12.0f)
                    reflectiveCurveToRelative(4.47f, 10.0f, 10.0f, 10.0f)
                    reflectiveCurveToRelative(10.0f, -4.47f, 10.0f, -10.0f)
                    reflectiveCurveTo(17.53f, 2.0f, 12.0f, 2.0f)
                    close()
                }
            }
            return _circle!!
        }
    
    private var _circle: ImageVector? = null
    And i wonder why doesn't it just use lazy initialization? As in something like this:
    public val Icons.Filled.Circle: ImageVector by lazy {
            materialIcon(name = "Filled.Circle") {
                materialPath {
                    moveTo(12.0f, 2.0f)
                    curveTo(6.47f, 2.0f, 2.0f, 6.47f, 2.0f, 12.0f)
                    reflectiveCurveToRelative(4.47f, 10.0f, 10.0f, 10.0f)
                    reflectiveCurveToRelative(10.0f, -4.47f, 10.0f, -10.0f)
                    reflectiveCurveTo(17.53f, 2.0f, 12.0f, 2.0f)
                    close()
                }
            }
        }
    Is it just a style issue? Or the second approach has hidden performance cost?
    z
    h
    • 3
    • 5
  • d

    Diego DeSouza

    11/20/2022, 3:04 PM
    Hi all, Im new to android development and going through this tutorial and getting hung up on this step
    sqldelight {
        database("AppDatabase") {
            packageName = "com.jetbrains.handson.kmm.shared.cache"
        }
    }
    while using Android studio, I’m not able to create a package like that, but directory instead, that looks like this.
    sqldelight {
        database("AppDatabase") {
            packageName = "com.example.ktorSQLDelight.shared.commonMain.sqldelight.shared.cache"
    //      packageName = "com.example.shared.cache"
        }
    }
    i called this project ktorSQLDelight, i tried the above, but my AppDatabase is never “found” by the rest of the app.
    h
    • 2
    • 15
  • d

    Diego DeSouza

    11/20/2022, 3:07 PM
    i have tried any combination of that path without avail
  • r

    Rob Elliot

    11/20/2022, 7:17 PM
    I don't suppose there's a way to abstract the declaration of the fields on an anonymous object is there?
    y
    • 2
    • 9
  • s

    Stefan Oltmann

    11/21/2022, 11:29 AM
    I'm looking for a way to calculate image similarity in Kotlin using cosine similarity. Does someone know a lib where this algorithm has already been implemented? The next best thing I was able to fnd is only a image hashing algorithm in Java which I could rewrite in Kotlin using skija. As far as I understood the cosine similarity algorithm has better results than image hashing, but I'm unfortunately now even able to find a Java implementation of this.
    s
    • 2
    • 3
  • x

    xun su

    11/21/2022, 1:50 PM
    Is
    String
    a primitive type ? if so , why I can use
    lateinit
    on it but not on
    Int
    ? the doc(https://kotlinlang.org/docs/properties.html#late-initialized-properties-and-variables) says
    The type of the property or variable must be non-null, and it must not be a primitive type.
    I got a error like this
    j
    m
    +3
    • 6
    • 51
  • x

    Xad Kile

    11/22/2022, 8:34 AM
    I have already checked, but just to be sure, allow me to ask: is there an immutable deque in Kotlin. There's ArrayDeque but it is not immutable. I am using LinkedBlockingDeque (a java implementation), but want to replace it with an immutable one.
    s
    k
    +3
    • 6
    • 9
  • h

    hfhbd

    11/22/2022, 10:20 AM
    Do you know any workaround to use objects with ServiceLoader? It requires a non-arg constructor, otherwise it will fail:
    Caused by: java.util.ServiceConfigurationError: Factory: Impl Unable to get public no-arg constructor
    and
    NoSuchMethodException: Impl.<init>()
    j
    p
    p
    • 4
    • 11
  • i

    Ian Lynagh

    11/22/2022, 1:25 PM
    Is it possible to give a more specific deprecation suppression here? I have had no luck putting just
    @Suppress("DEPRECATION")
    anywhere
    $ cat Test1.kt 
    @file:Suppress("DEPRECATION")
    
    import foo.Bar
    $ cat Test2.kt
    package foo
    
    @Deprecated(message = "Bar is deprecated")
    interface Bar
    $ kotlinc -Werror Test1.kt Test2.kt
  • a

    Adrian Amiel Sanchez

    11/22/2022, 4:53 PM
    Hi, I want to define a factory for an interface for a common library. I want to understand the pros/cons of defining a concrete class vs using anonymous object. Can’t wrap my head on the lines in Object expressions regarding anonymous classes:
    Such classes are useful for one-time use
    .
    interface Person {
        val name: String
        val age: Int
    }
    
    Option 1
    ---
    fun Person(name: String, age: String): Person = object : Person {
        override val name = name
        override val age = age
    }
    
    Option 2
    ---
    fun Person(name: String, age: String): Person = PersonImpl(name, age)
    
    private class PersonImpl(
        override val name: String,
        override val age: String
    ) : Person
    1. What’s the pros/cons between the two? 2. Which is more preferred? 3. What does
    one-time use
    mean? Does it mean we can’t pass instances of anonymous classes around?
    a
    c
    k
    • 4
    • 8
  • y

    y

    11/23/2022, 5:39 PM
    when debugging Kotlin with IntelliJ, is it possible to go back to some point in a previous frame?
    s
    k
    • 3
    • 2
  • s

    Sam Stone

    11/24/2022, 3:32 AM
    How can i exclude data class field from hash code and equals?
    c
    j
    • 3
    • 5
  • t

    theapache64

    11/24/2022, 10:25 AM
    Is there any particular reason why companion object should be at the bottom? Or it’s just a convention ?
    j
    l
    x
    • 4
    • 22
  • r

    Robert Jaros

    11/24/2022, 6:33 PM
    When is the release of Kotlin 1.8.0 planned?
    h
    • 2
    • 1
  • s

    Sen Ichi

    11/24/2022, 9:02 PM
    hi! i’m new to kotlin and KMM and i’m trying to create a multiplatform app using this android library but i’m still confused about how to setup everything. i even opened up a stack overflow ticket about it but i’m still not clear about how it works? i’m supposed to add the dependency in the androidApp module and then create a common api in commonMain and then platform-specific code in iosMain and androidMain?
    i
    e
    • 3
    • 9
Powered by Linen
Title
s

Sen Ichi

11/24/2022, 9:02 PM
hi! i’m new to kotlin and KMM and i’m trying to create a multiplatform app using this android library but i’m still confused about how to setup everything. i even opened up a stack overflow ticket about it but i’m still not clear about how it works? i’m supposed to add the dependency in the androidApp module and then create a common api in commonMain and then platform-specific code in iosMain and androidMain?
i

Igor Milakovic

11/24/2022, 9:04 PM
Not sure if that helps, but this is a fantastic starter project: https://github.com/touchlab/KaMPKit
e

Evegenii Khokhlov

11/25/2022, 2:47 PM
I hope I am not confused you with my answer. Try to explain here, we can update my answer together and make it clear for others Your starter KMM application has 3 parts: •
androidApp/
- contains your Android application. It has starting point of your Android application •
iosApp/
- contains your iOS application. It has starting point of your iOS application •
shared/
- its just shared library which compiles both to Android and iOS and can be used in your Android and iOS applications So when you want to add library which is designed for Android only, your are adding it directly to Android app. The same is for iOS. Is it a little bit more clear?
s

Sen Ichi

11/27/2022, 6:19 PM
yeah, it is clear but i’m still having trouble implementing >< here’s my androidApp build.gradle dependency list:
e

Evegenii Khokhlov

11/28/2022, 11:08 AM
And what kind of trouble do you have with this setup? Basically your dependencies looks a little bit odd, because your declare compose libraries and then again add Android View version of this Calendar library (although it has compose version too)
s

Sen Ichi

11/28/2022, 5:08 PM
@Evegenii Khokhlov well, the Calendar library isn’t being recognized. i thought it might be that i hadn’t downloaded the sources for the specific compileSDK i’m using, and so i did that but nothing changed.
e

Evegenii Khokhlov

11/28/2022, 5:11 PM
where exactly it hasn’t been recognized, in androidApp module?
s

Sen Ichi

11/28/2022, 6:20 PM
@Evegenii Khokhlov yes - in the screenshot i sent, that is the build.gradle dependency list in the androidApp module. it says no documentation found
e

Evegenii Khokhlov

11/29/2022, 1:52 PM
I believe this message doesn’t necessary mean, that library hasn’t been recognized. Have you got any errors on run? And also have you added the JitPack repository, according to the documentation of the library?
s

Sen Ichi

11/29/2022, 8:46 PM
@Evegenii Khokhlov oh lol. well that’s my fear of making any changes/steps unless i am 100% sure of what’s going on ! please excuse me haha. and yes! i had added the jitpack link to my settings.gradle and build.gradle files already
View count: 4