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

    Jason5lee

    05/01/2021, 2:42 PM
    Why
    kotlin.io.AccessDeniedException
    isn’t a alias of
    java.nio.AccessDeniedException
    on JVM? Why creating such a new class that might confused the user that tries to catch this exception?
    n
    • 2
    • 6
  • t

    thhh

    05/02/2021, 2:12 PM
    Why does removing "redundant initializer" as suggested by IntelliJ in this code: https://pl.kotl.in/7Kcy18ROA drastically increases the time required to run the program? The
    time
    variable has a redundant initializer which is commented. When you uncomment and use that redundant initializer, program runs a lot faster. Findings: when using redundant initializer: 20000100000 in 28ms --> which is quite fast. when removing redundant initalizer: 20000100000 in 103ms --> which is slow but is recommended by IntelliJ. IntelliJ hint aside what causes the Kotlin program to run "slower" when NOT using redundant initlializer?
    d
    • 2
    • 3
  • t

    thhh

    05/02/2021, 4:35 PM
    When using
    thread
    , the result is expected but when using
    launch
    from Kotlin coroutine, the result is wrong and not expected. Code: https://pl.kotl.in/cBD4j9XWb In the code, as expected when using the
    thread
    code in the for loop, the result prints 15000 but when using
    launch
    for loop, the result prints 0 !? which is not expected. Why is this happening and why
    launch
    is giving wrong answer?
    e
    • 2
    • 5
  • s

    Slackbot

    05/04/2021, 6:54 PM
    This message was deleted.
    c
    c
    +2
    • 5
    • 8
  • s

    Sangmin Lee

    05/05/2021, 7:48 AM
    Hi, I’m from python and newbie to kotlin/java. I’m wondering how to assign different annotation to variable and call function with it.
    var metadata = field.getAnnotation(AnnotationA::class.java) ?: field.getAnnotation(AnnotationB::class.java)
    if (metadata != null) {
        someFunction(metadata) // which has two overrided functions with AnnotationA and AnnotationB
    }
    Compiler says “None of the following functions can be called with the arguments supplied.” and it says metadata is casted to ‘Annotation!’ How can I set metadata AnnotationA or AnnotationB, and use my overrided function according to the type?
    t
    • 2
    • 3
  • h

    Helio

    05/06/2021, 8:02 AM
    Hello 👋🏽 , Apologies if this is a silly question, but would anyone be able to help me understand what this error
    Cannot use 'T' as reified type parameter. Use a class instead.
    means in this situation? I’m trying to generalise the
    decodeFromString
    and
    encodeFromString
    but I’m confused why it doesn’t let me do that.
    @ExperimentalLettuceCoroutinesApi
    abstract class RedisDAO<T>(
        private val keyPrefix: String,
        private val ttl: Long, private val redisClient: BbcRedisClient
    ) {
    
        open suspend fun getValueFromKey(key: String): T? {
            val extractedValue = redisClient.getValueFromKey(key)
            return extractedValue?.let { Json.decodeFromString<T>(it) }
        }
    
        open fun buildRedisKey(identifier: String): String {
            return "$keyPrefix$identifier"
        }
    
        open suspend fun saveWithTTL(key: String, value: T) {
            val encodedValue = Json.encodeToString<T>(value)
            redisClient.storeKeyWithTTL(key, encodedValue, ttl)
        }
    }
    r
    • 2
    • 3
  • s

    Steven

    05/06/2021, 4:45 PM
    Any ideas on why Micronaut ignores my test when I add the decorator
    @MicronautTest
    ?
    @MicronautTest( environments = [ "Test"])
    class RequestHandlerTestLocal: DescribeSpec ({
    
        lateinit var applicationContext: ApplicationContext
        describe("Lambda Tests") {
    
            it("Creates correct Audit errors") {
    //            println( "hello-world" + applicationContext.environment )
                //TODO
            }
        }
    })
    result is an ignored test.
    d
    • 2
    • 1
  • h

    Helio

    05/12/2021, 2:45 AM
    Untitled.kt
    e
    a
    • 3
    • 38
  • d

    Daniele B

    05/12/2021, 7:24 AM
    Is there any way by which, having a
    List<String>
    like this:
    val myList = listOf("paramA","paramB","paramC")
    I can enforce an API like this?
    fun myFunc (paramA: String, paramB: String, paramC: String)
    basically a function, which has those strings as names for String arguments?
    v
    e
    +3
    • 6
    • 35
  • d

    Daniele B

    05/12/2021, 12:37 PM
    how can I pass a property to a companion object?
    m
    a
    • 3
    • 4
  • p

    Pepijn de Vos

    05/13/2021, 10:38 AM
    I want to get started with Kotlin for JS, and generally use VS Code for all my other development. It seems the docs are only concerned with InteliJ. Does it make sense to try to use VS Code or is kinda required to use InteliJ for a good experience?
    d
    r
    • 3
    • 2
  • r

    Ruckus

    05/13/2021, 9:11 PM
    Question about floor division and mod. My mental model is basically splitting the number line into chunks of a given size.
    mod
    tells you how far into a chunk you are, and
    floorDiv
    tells you which chunk you are in. Is getting the start of the given chunk as simple as
    floorDiv * chunkSize
    ? Is it more complicated than that? Is my mental model fundamentally wrong?
    e
    • 2
    • 12
  • a

    Andrew Ebling

    05/14/2021, 10:21 AM
    How do I store instances of an
    enum class
    implementing an interface in a
    TreeMap
    such a way that I can set/get set them without throwing a
    ClassCastException
    ? So far I have:
    interface MyEnumInterface {}
    
    enum class MyEnumClass: MyEnumInterface { ... }
    var myTreeMap: TreeMap<MyEnumInterface, (() -> (Unit))> = TreeMap()
    however when I call this method, passing an instance of `MyEnumClass`:
    fun add(howToExecute: () -> (Unit), myEnum: MyEnumInterface) {
       myTreeMap[myEnum] = howToExecute // ClassCastException here
    }
    ... I get a
    ClassCastException
    . Why does this happen? Why doesn’t it happen when the instance is passed to the add() method? What’s the most appropriate resolution please?
    🤔 1
    d
    k
    • 3
    • 13
  • d

    Daniele B

    05/17/2021, 7:44 PM
    is there a list structure in Kotlin which keeps distinct values only?
    e.g.  val list = listOf(3,9,1,6,7)
    if I add a new 9, it would removes the old one:
    list.add(9)
    println(list) // listOf(3,1,6,7,9)
    c
    e
    s
    • 4
    • 9
  • d

    Daniele B

    05/18/2021, 9:52 AM
    I would like to get a list of the values, ordered by the map key:
    val a = mapOf(2 to "W", 3 to "V", 1 to "T")
    desired result:
    val list = listOf("T","W","V")
    I was reading you can do that using
    sortedMap
    , but it doesn’t come out on the IDE.
    e
    w
    +3
    • 6
    • 20
  • s

    Soe

    05/18/2021, 10:24 AM
    Hello everyone, this is my first message, I'm planing to learn Kotlin as my first programming language.
    :kotlin-flag: 11
    👋 12
    m
    a
    • 3
    • 2
  • e

    evkaky

    05/20/2021, 10:10 AM
    Hello everyone. I was quite surprised that the following code doesn’t get compiled
    val map = mutableMapOf("key1" to 1)
    map["key1"] += 2
    Why Is it not possible to use increment in such a way?
    👀 3
    h
    r
    +4
    • 7
    • 16
  • j

    Justin Yue

    05/24/2021, 11:48 PM
    I'm starting off w/ Kotlin, and I was wondering for retrieving console input, is it preferable to use
    readLine()
    from the kotlin.io package or to use `Scanner(System.
    in
    )` from the java.io package? I think my personal preference is going the Java route because I feel that returning
    String?
    from
    readLine()
    is something I don't want to deal with. But maybe I'm not using Kotlin's null safety as much as I should be?
    m
    j
    • 3
    • 7
  • o

    oday

    05/25/2021, 2:19 PM
    so I have a list of orders and then a list of cars, when I get the list of cars I would like to take from it all the cars whose
    id
    exists in the list of orders
    d
    m
    • 3
    • 18
  • t

    thhh

    05/25/2021, 4:50 PM
    What does
    Stub!
    means? In kotlin code, I tried to see the Declaration of Exception. In there, I found a
    Stub!
    string. What does it mean. Image:

    https://i.imgur.com/6WX2nfQ.png▾

    h
    • 2
    • 1
  • m

    maarten ha

    05/25/2021, 8:44 PM
    Could someone please help me out with some gradle stuff? the issue I’m having is that apollo (graphql client) generates inline bytecode or somthing because I have an error that says :
    Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper '-jvm-target' option
    Adding support for Java 8 language features could solve this issue.
    The app is an kmm project. In both the shared build as the android build file is the compileOptions with javaversion 1.8 set but still getting the error I don’t know gradle that well and if I need to place this somewhere else let me know
    t
    • 2
    • 2
  • c

    Colton Idle

    05/26/2021, 5:43 PM
    Got this pop up in AS and it 404s. What am I doing wrong?
    m
    • 2
    • 3
  • m

    mario

    05/26/2021, 7:50 PM
    Hello everyone, I am android dev and I interested in android compose and android news for developers, what channels do you recommend me?
    b
    • 2
    • 1
  • w

    wydra91

    05/27/2021, 7:36 AM
    Sorry, I didn't mean to send that, but I keep getting that alert in the build and I don't know what is going on or why I'm getting it. Am I doing something wrong when setting up the project?
    r
    • 2
    • 8
  • w

    wydra91

    05/27/2021, 8:10 AM
    Okay, finally got a valid output. Looks like I'm running Gradle 6.8
    z
    c
    • 3
    • 67
  • d

    Dennis Tel

    05/27/2021, 2:02 PM
    Hi! Is there a good persistence library (preferably a Kotlin one) for working with postgres’s json columns?
    👀 1
    h
    c
    • 3
    • 7
  • r

    Ruckus

    05/27/2021, 5:14 PM
    Is there any reason to prefer
    fun main(args: Array<String>)
    over
    fun main(vararg args: String)
    ?
    r
    s
    +2
    • 5
    • 25
  • z

    Zan Skamljic

    05/28/2021, 8:34 PM
    how about
    blockList.all { name.contains(it, true) }
    ?
    :thread-please: 1
    e
    c
    +2
    • 5
    • 7
  • a

    Andrea Giuliano

    06/02/2021, 8:35 AM
    Hi guys, given a mutableSet, I’d like to remove all the items from a collection, and then just get X items from it. For example
    myMutableSet.removeAll(collection)
    myMutableSet.take(x)
    now I’d like not to use take since the set can contain millions of items and I’d like not to copy all in a new set..any suggestions? There is no constraints on the “which” X items to take..random is fine
    u
    • 2
    • 2
  • p

    phisch

    06/02/2021, 1:18 PM
    I am facing the issue that IntelliJ doesn't let me use
    mutableListOf
    inside of
    commonMain
    . I can use it in every other directory (
    commonTest
    ,
    nativeMain
    and
    nativeTest
    ). I have reinstalled the IDE, the Kotlin plugin, disabled all other plugins, tried the EAP and created multiple new projects to test this, and it is always the same issue. Here is a video showing that this doesn't work in `commonMain`:
    t
    • 2
    • 10
Powered by Linen
Title
p

phisch

06/02/2021, 1:18 PM
I am facing the issue that IntelliJ doesn't let me use
mutableListOf
inside of
commonMain
. I can use it in every other directory (
commonTest
,
nativeMain
and
nativeTest
). I have reinstalled the IDE, the Kotlin plugin, disabled all other plugins, tried the EAP and created multiple new projects to test this, and it is always the same issue. Here is a video showing that this doesn't work in `commonMain`:
Also here is a screenshot that shows a popup telling me that
mutableListOf
will not be available in
commonMain
when copying this test class to `commonMain`:
Oh man, this is so frustrating... it's actually a deal-breaker -.-
t

Timo Gruen

06/02/2021, 2:03 PM
You shouldn’t use the package names you are using:
src/org/example/app
should be the “main” package of your application / code. Btw. tests are not in the
src
module, instead one typically has a
test
module with the same package structure like your
src
:
test/org/example/app
I woul dassume Intellij is not working properly, since you are having a package named
*main
which might collide with some internal logic of intellij.
p

phisch

06/02/2021, 2:06 PM
This is an auto generated kotlin native project @Timo Gruen
Also sometimes when i open intellij, it finds
mutableListOf
in
commonMain
and then when i restart it, it doesn't find it again. Its completely random, idk.
t

Timo Gruen

06/02/2021, 2:08 PM
Ahhh in that case just ignore me. Never worked with kotlin native yet. Assumed you tried to run JVM Kotlin
You already tried to refresh the cache? Helped me plenty of times in the past with IntelliJ
p

phisch

06/02/2021, 2:09 PM
Yes, i also tried re-installing the IDE and plugins and creating new fresh projects, always the same random result.
If anyone stumbles over this, i am convinced this is a but with IntelliJ or the Kotlin plugin, and i opened an issue for it: https://youtrack.jetbrains.com/issue/IDEA-270688
View count: 4