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
announcements
  • p

    Philipp Hanslovsky

    03/20/2021, 3:08 PM
    Hi team, I have a Kotlin JVM project that depends on
    org.jetbrains.kotlin:kotlin-compiler-embeddable:jar:1.4.30:compile
    , which introduces the JetBrains trove4j fork
    org.jetbrains.intellij.deps:trove4j:jar:1.0.20181211:runtime
    as a transitive dependency. (entire dependency tree in thread). One of the usage scenarios installs the jars and transitive dependencies into a program that already has GNU
    trove4j
    as a dependency, but in an incompatible version. What is the best way to avoid dependency clashes here? I tried shading all of
    kotlin-compiler-embeddable
    and the jetbrains
    trove4j
    into the jar that I generate for installation and it works. Is this the recommended way to solve this clash between jetbrains
    trove4j
    fork and GNUE
    trove4j
    ? If anyone has examples, I would like to take a look at those to make sure, I only include the dependencies necessary and also don't leave out anything.
    j
    • 2
    • 3
  • t

    therealbluepandabear

    03/20/2021, 8:31 PM
    Does anyone want to code with me? I am looking to test the new 'code with me' feature on IntelliJ 2021.
    d
    b
    t
    • 4
    • 30
  • d

    Dominick

    03/21/2021, 5:57 AM
    enum class PacketType(val id: Short, vararg aliases: String) {
        CUSTOM_PAYLOAD(0), KEEP_ALIVE(1), LATENCY(2);
    
        companion object {
            private val PACKETS_BY_ID = mutableMapOf<Short, PacketType>()
            private val PACKETS_BY_ALIAS = mutableMapOf<String, PacketType>()
    
            fun fromId(id: Short): PacketType? = PACKETS_BY_ID[id]
            fun fromName(id: String): PacketType? {
                return try {
                    valueOf(id)
                } catch (e: IllegalArgumentException) {
                    PACKETS_BY_ALIAS[id]
                }
            }
        }
    
        init {
            PacketType.PACKETS_BY_ID[id] = this
            for (alias in aliases) {
                PacketType.PACKETS_BY_ALIAS[alias] = this
            }
        }
    
        operator fun get(id: Short) = fromId(id)
        operator fun get(id: String) = fromName(id)
    }
    For some reason, PACKETS_BY_ID and PACKETS_BY_ALIAS don't get initialized
    r
    • 2
    • 2
  • d

    Danish Ansari

    03/21/2021, 8:44 AM
    Ok this might be a little dumb question but here we go I'm creating an extension property on
    androidx.compose.material.Colors
    class which should be changed later that's why I have used
    var
    var Colors.warning: Color
        get() = Color(0xFFFFC107)
        set(value) {
            field = value
        }
    But I'm getting error in the setter
    Unresolved reference: field
    Dunno how to handle this scenario
    k
    • 2
    • 2
  • f

    franztesca

    03/21/2021, 11:35 AM
    import kotlin.jvm.internal.Reflection
    
    inline fun <reified T: Number>round(number: T): Int {
        return when(T::class){
            Int::class -> number as Int
            Double::class -> (number as Double).toInt()
            else -> throw IllegalArgumentException("Invalid type")
        }
    }
    
    fun test(){
        print(round(1))
        print(round(2.0))
        print(round(3f))
    }
    
    fun howShouldBeCompiled(){
        print(1)
        print((2.0 as Number).toInt())
        throw IllegalArgumentException("Invalid type")
    }
    
    fun howItIsCompiled() {
        val number = 1
        val type = Reflection.getOrCreateKotlinClass(Int::class.java)
        var result1: Int = when(type){
            Int::class.java -> number
            Double::class.java -> (number as Double).toInt()
            else -> throw java.lang.IllegalArgumentException("Invalid type")
        }
        print(result1)
        
        //... do the same for each case
    }
    Is there a way to inline reified generic functions at compile time? Isn't T::class known at compile time? The only alternative which I see is removing the generic and manually overload each possible accepted class (in this case it's just two, but I have more complex cases with like 8 input classes). I feel like having only one function declaration with a switch (when) is more elegant than 8 declarations with overload (for simple functions).
    y
    • 2
    • 1
  • c

    christophsturm

    03/21/2021, 1:30 PM
    it seems default parameters for generic types need a space before the equals sign. is this a bug or is it documented somewhere?
    y
    a
    • 3
    • 3
  • d

    dephinera

    03/21/2021, 2:43 PM
    The following construct confuses me.
    interface Scope
    
    class Service : Scope {
    
        fun <T> scoped(block: Service.() -> T): T {
            return block().also {
                finalize()
            }
        }
    
        fun Scope.foo(): String {
            return "Heya!"
        }
    
        private fun finalize() {
            // release resources and stuff
        }
    
    }
    
    fun main() {
    
        val service = Service()
    
        val res = service.scoped {
            foo()
        }
    
        service.foo() // ERROR
    }
    Basically I achieved what I wanted - to be able to call Service's methods only within a scope, so some finalization work can be done automatically, instead of relying on the consumer to do it. However I don't really understand why I can't call
    foo
    outside the scope. Can anyone explain it, please?
    y
    s
    • 3
    • 4
  • s

    samuel

    03/21/2021, 8:31 PM
    Is it possible to use reflection to get extension functions for
    String
    such as
    toInt
    toLong
    etc?. I can see the file and package they are contained in here but i am not sure how to actually access them, could anyone provide a hint?
    y
    • 2
    • 4
  • m

    Michael S.

    03/21/2021, 8:59 PM
    Hello. I noticed that if I try to create a new object of an inner class with a null safe call I get an exception but if I do that using the
    let()
    function it works fine even though the IDE is complaining about it. Is this intended behavior?
    a
    • 2
    • 2
  • r

    Robert

    03/21/2021, 9:11 PM
    Hi, I'm looking for an Android Engineer with a strong background in Kotlin. Is this the best place to post a job, or is there a more appropriate channel for that?
    b
    • 2
    • 2
  • t

    TwoClocks

    03/22/2021, 5:46 AM
    I'm trying to call get() on a property via reflection. I pass an instance of the class in question to get() and I get the error
    Type mismatch: inferred type is MessageDispatch but Nothing was expected
    what's a
    nothing
    ? And the docs say it should be an instance of the class... which it is.. very confused.
    r
    y
    • 3
    • 17
  • k

    Karlo Lozovina

    03/22/2021, 12:16 PM
    does Kotlin have some sort of conditional compilation? i have some code (scattered around) that would like to have present while developing, but not be there in final releases, is there a way to do that?
    k
    n
    • 3
    • 4
  • r

    Rooparsh

    03/22/2021, 12:36 PM
    🆘 Require knowledge from all the Kotlin Gurus. I was looking into a JavaScript code and found the following syntax
    const {a , …remaining} = user
    …
     is called spread operator in JavaScript Where
    user = {a : "12", b : 2 , c: "Some random String"}
    so the value of 
    user.a
     was copied in variable 
    a
     and all the remaining keys of user object 
    user.b
     and 
    user.c
     were copied in 
    remaining
     variable. This concept is called 
    Destructuring
      and in kotlin world, the nearest possible syntax that I know, is
    val (a,b,c) = user
    But, can we write this anyway better without declaring 3 variables ??? So, that my final code should be
    val (a,remaining) = user
    t
    s
    • 3
    • 5
  • f

    Fábio Carneiro

    03/22/2021, 1:13 PM
    how can I flip a boolean state in a given interval (every 2 min)?
    d
    r
    • 3
    • 2
  • l

    Luca Piccinelli

    03/22/2021, 2:11 PM
    Hello everyone! Could please anyone point me to a detailed documentation on how to use Kapt server side, possibly with maven? I found a lot of articles but they are all Android oriented....
    t
    • 2
    • 3
  • c

    Cdev

    03/22/2021, 7:55 PM
    I have a KMM project with Sealed classes and classes inside of those, to represent some state. On the Kotlin side it's idiomatic to use a "when" statement on these. On the swift side the best I could come up with were switch statements and it doesn't seem to realize that my cases are exhaustive and instead requires me to add a "default:" case. Is this a limitation of the what KMM sealed classes compile down to in their Swift interop? let menuStyle = projectConfig.settings.appearance.menuStyle       switch menuStyle {       case (is Settings.AppearanceMenuStyleBottom):         print("Bottom Menu")         break       case (is Settings.AppearanceMenuStyleSlideOut):         print("SlideOut Menu")         break       case (is Settings.AppearanceMenuStyleTiled):         print("Tiled Menu")         break       default: print("Swift requires this even though the sealed class is exhausted")       }
    e
    d
    • 3
    • 5
  • t

    therealbluepandabear

    03/23/2021, 2:25 AM
    Can you use Java libraries such as LibGDX with Kotlin for game development? I heard there is something called 'libKTX' - can we use 'libKTX' (Kotlin extensions for LibGDX) standalone, or does it need to be combined with LibGDX?
    :google: 3
    m
    v
    n
    • 4
    • 4
  • h

    Holger Steinhauer [Mod]

    03/23/2021, 8:34 AM
    Hey folks. Anyone with experience in proto buffers here?
    n
    j
    +3
    • 6
    • 15
  • j

    jvmusin

    03/23/2021, 10:56 AM
    Hello! My Dependabot just told me that Kotlin
    1.4.32
    is out, but there are no announcements and no new releases out on GitHub. P.S. Well, basically it said that
    serialization
    and
    multiplatform
    plugins are updated to
    1.4.32
    , seems like the language is not updated yet, but the plugins are.
    c
    p
    e
    • 4
    • 3
  • d

    df

    03/23/2021, 11:23 AM
    Is there an easy way to merge two maps of Map<String, Foo> into one map? I know the keys of the two maps are distinct from each other. I.e. I don't want to have Map<String,List<Foo>> as a resulting map.
    r
    d
    n
    • 4
    • 24
  • r

    Rob Elliot

    03/23/2021, 11:52 AM
    When using
    lateinit var
    on the JVM on a field on an object used from more than one thread do you also need
    @Volatile
    to prevent other threads seeing it as null, or do you get that for free?
    • 1
    • 1
  • m

    Mehdi Haghgoo

    03/23/2021, 12:28 PM
    What kind of inheritance is this? I see it in Compose docs, but can't find its usage on Kotlin docs. Can a subclass (object) be defined inside the parent class?
    :yes: 1
    m
    • 2
    • 3
  • l

    landon burch

    03/23/2021, 3:59 PM
    I am looking for help with ktor and didn't know which channel was a good channel to go to .. so if someone can direct me to the best channel I would appreciate .
    s
    • 2
    • 2
  • s

    ShootingStar

    03/23/2021, 5:40 PM
    Hello, I can’t compile the following code with Kotlin 1.2.71. However, the code compiled well with Kotlin 1.2.30 even though the same error message shows in my IntelliJ (with red underline).
    Restricted suspending functions can only invoke member or extension suspending functions on their restricted coroutine scope
    Can I get some advice?
    @RestrictsSuspension
    abstract class Service() {
        protected suspend inline fun yieldAsync() { ... }
        protected abstract suspend fun start()
    
        private suspend fun startWrapper() {
            yieldAsync()
            start()
        }
    
        private fun <T> launchCoroutine(block: suspend () -> T) = block.startCoroutine(...)
    
        final override fun onLifecycleStart() {
            launchCoroutine { startWrapper() } // <- error spot startWrapper()
        }
    }
    n
    • 2
    • 1
  • a

    Ademir Queiroga

    03/23/2021, 8:58 PM
    Hi folks, question about annotation processing. Anyone knows how to read the annotations of the properties in a interface when processing the interface class?
    @Model
    interface Config {
        @Prop(name = "renamedConfigField")
        val configField: String
    }
    When processing the Config interface I would like to be able to iterate over it’s properties (which I’m already doing) but I’m not being able to read the fields annotations (e.g. read the @Prop annotation on the
    configField
    )
    t
    • 2
    • 19
  • d

    Danilo Lima

    03/23/2021, 10:30 PM
    I had the same doubt. Where or how could this be useful? Would anyone here know how to give a tip? This is the tweet: https://twitter.com/pablisc0/status/1374468084916908041
    j
    e
    p
    • 4
    • 7
  • j

    Juan B

    03/23/2021, 11:12 PM
    Hi all, I have a question about extension functions, I'm kind of stuck. Hope anyone can point me in the right direction. The problem I'm trying to solve: I want to be able to check when a property in a data class has been set. The goal is to be able to differentiate between a null value (the property has been set to null) and a non present (value was not set). A potential use case is to implement a HTTP Patch where you receive Input Objects as DTO and you want to save in the database entities only the properties set in the DTO. My initial approach: I thought it could be solve with a delegate using a map, so I could use the map to check if the value was actually set. Here is some code, but it is not working.
    class InputExample(val map: Map<String, Any?>) {
            val name: String? by map
            val age: Int?     by map
            val lastname: String? by map
    
            fun KProperty<Any>.isPresent(): Boolean {
                //return map.containsKey(this.name)
                return true
            }
     }
    I was trying to get to a interface like this:
    inputType.lastname.isPresent()
    e
    n
    +3
    • 6
    • 22
  • b

    Before Old

    03/24/2021, 1:59 AM
    Hi there, my team is new to kmm, have a question about publishing a kmm framework from ios side. if we want to track the uncaught exception trace of kotlin, do we have to publish a debug framework instead of a release one? (we have read issues and docuement about this, not so sure) https://github.com/JetBrains/kotlin-native/issues/2600 https://kotlinlang.org/docs/native-ios-symbolication.html
    a
    • 2
    • 1
  • b

    Brian Dilley

    03/24/2021, 5:04 AM
    best linter available for kotlin with gradle / intellij support?
    r
    e
    • 3
    • 5
  • p

    Peter Ertl

    03/24/2021, 2:09 PM
    when reading unicode characters from an StringReader, should I use method #read() returning [Int] values or is there something else to convert the characters into [kotlin.Char] first ? what is the correct way to represent unicode code points?
    r
    e
    • 3
    • 21
Powered by Linen
Title
p

Peter Ertl

03/24/2021, 2:09 PM
when reading unicode characters from an StringReader, should I use method #read() returning [Int] values or is there something else to convert the characters into [kotlin.Char] first ? what is the correct way to represent unicode code points?
r

Ruckus

03/24/2021, 2:18 PM
That's the correct method. The reason it returns
int
instead of
char
is so it can return a
-1
if you've reached the EOI.
p

Peter Ertl

03/24/2021, 2:18 PM
so basically, after removing -1 Char and Int are equivalent?
kotlin could probably provider a “nicer” method readChar(): Char? instead I guess
since using Int for delivering -1 as a sentinel value feels like a quirk
r

Ruckus

03/24/2021, 2:19 PM
This is a Java API, not a Kotlin API. On the JVM all primitives < 32 bits are internally `int`s.
p

Peter Ertl

03/24/2021, 2:20 PM
yeah, I was just thinking of an extension method… thanks for clarifying this, Ruckus 🙂
I just do it like this now:
input.read().takeIf { it != -1 }?.toChar()
r

Ruckus

03/24/2021, 2:21 PM
Meh, it's not really any different than any other sentinel value, and has the advantage that it's returning a primitive value, so there's no need for object allocation etc.
That will work, but it will box the
Int
and the
Char
. Whether that matters is entirely dependent on your use case. In general it's most likely fine, but worth keeping in mind if it's in a hot loop and you see any performance issues.
p

Peter Ertl

03/24/2021, 2:22 PM
I use it to implement a tokenizer used by a parser to evaluate expressions
thanks a lot for helping 🙂
👍 1
r

Ruckus

03/24/2021, 2:27 PM
I agree it would be a much cleaner API to use some sort of
Option
or
Result
type, but unfortunately those aren't free on the JVM.
p

Peter Ertl

03/24/2021, 2:28 PM
with the introduction of value classes it will probably come sooner or later
^ which are currently experimental afaik
‘value class Option<T>’ for the world :-)
r

Ruckus

03/24/2021, 2:30 PM
I doubt it. There's way too much legacy in place to change that, and using
-1
as a sentinel is such a well established standard in Java at this point I doubt many will see the need (or want) to change it. I could be wrong though...
Even the lowly
indexOf
uses it.
p

Peter Ertl

03/24/2021, 2:32 PM
true … legacy vs modern api = 1:0 i guess 😛
r

Ruckus

03/24/2021, 2:33 PM
That's my guess, yeah
👍 1
e

ephemient

03/24/2021, 4:07 PM
even Kotlin's
indexOf()
uses -1 as a sentinel. that will stay unless there's an inexpensive alternative
View count: 4