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

    TheDukerChip

    03/24/2021, 4:04 PM
    Hi guys, Can anyone point me out for the equivalent of the following Java code in Kotlin?
    public <T extends AbstractSomething & InterfaceSomething> ConcreteClass(manager T)
    n
    • 2
    • 2
  • n

    nanodeath

    03/24/2021, 4:13 PM
    I'm sure (or hoping) that this has been brought up before, but the SEO of the new Kotlin documentation portal is terrible. if you Google for "Kotlin generics", you don't get any official Kotlin docs until the second page of results, and even then those results aren't for "/docs/generics.html", they're for less-related doc pages. anyone aware of an open issue for this?
    s
    t
    • 3
    • 3
  • p

    PHondogo

    03/24/2021, 5:33 PM
    Hello! How can i force compiler to restrict 'when' expression if not all branches specified and it is not returning or assigning?
    🙄 1
    e
    c
    v
    • 4
    • 7
  • s

    Sumeet Parmar

    03/24/2021, 8:51 PM
    hi- in my java project with gradle
    6.8.3
    , I’m getting nagged on kotlin
    1.4.20
    vs
    1.4.30
    — I’m going to downgrade to kotlin-1.4.20 everywhere, is there a better solution?
    e
    t
    • 3
    • 9
  • t

    therealbluepandabear

    03/24/2021, 11:04 PM
    When coding in Kotlin, do you guys use Git CMD or just use the automatically integrated version-control system in IntelliJ (if you know what I'm talking about)?
    s
    b
    +8
    • 11
    • 46
  • l

    Lukas K-G

    03/25/2021, 5:45 AM
    I am using
    @Deprecated(...)
    in my Kotlin library but from a plain Java project, the deprecation is not shown. Is that a known issue or is there anything wrong with my setup? 🤔
    a
    • 2
    • 6
  • m

    Michał Kalinowski

    03/25/2021, 12:03 PM
    Is there any channel for Skiko/Skija that are JetBrains binding for Skia?
    o
    • 2
    • 1
  • u

    user

    03/25/2021, 1:13 PM
    viktor: Efficient Vectorized Computations in Kotlin Introducing viktor viktor is an open-source Kotlin library developed by JetBrains Research that aims to make array calculations more efficient. We achieve this by avoiding nested arrays, delegating expensive operations to JNI + SIMD, and providing built-in support for arithmetics on logarithmically-stored numbers. This post is in celebration of the 1.1.0 release. We will discuss […]
    👍 3
    k
    • 1
    • 1
  • j

    jaqxues

    03/25/2021, 2:27 PM
    I want to make a file parser for some file format for best possible speed, preferably multithreaded. The question is, would writing it in Kotlin/Native instead of C/++ hurt its performance? I suppose Kotlin/Native is fairly slower than C++, but what are your opinions?
    b
    r
    • 3
    • 5
  • i

    Igor Akkerman

    03/25/2021, 2:55 PM
    Hi, IntelliJ IDEA shows an error when the code references `KClass`:
    Class 'kotlin.reflect.KClass' is compiled by a pre-release version of Kotlin and cannot be loaded by this version of the compiler
    I'm using Kotlin 1.5.0-M1 in the latest EAP of the IDE with Kotlin plugin targeting 1.5.0 turned on, the project is built using Gradle. `KClass`seems to be referenced correctly by the IDE as coming from the 1.5.0-M1 JAR. Has anybody seen this error before?
    a
    • 2
    • 17
  • m

    Marcin Wisniowski

    03/26/2021, 12:25 AM
    Hello, I am trying to return a lambda with a receiver from a
    when
    statement, but it doesn't seem to work, the receiver does not register. How can I make this work?
    n
    o
    +2
    • 5
    • 11
  • m

    Mikhail Galanin

    03/26/2021, 8:52 AM
    Hello, I’m thinking of using Kotlin as a code generation tool for different languages (currently aiming on php and golang). I believe it should be possible, there are already backends for JS and Native. I was wandering if there is any specification/documentation about compiler backends or someone could guide me to better understanding how to start exploring current implementations?
    t
    • 2
    • 12
  • e

    elect

    03/26/2021, 12:25 PM
    sorry if this is not really kotlin specific, but how can I install the jetbrain sdk JBRSDK8?
    • 1
    • 1
  • v

    Vladimir Bondarev

    03/26/2021, 1:06 PM
    Hey! There is a problem in the code generation of interfaces from Common for use in the Swift implementation. Different interfaces have the same method name and signature. The KMM generates names and adds "_" to each subsequent method that has the same signature. Who has already had this problem? Do you have a solution?  interface abcde { fun initialize(reference: ObjectReference) }  interface gfjk { fun initialize(reference: ObjectReference) } code generation interfaces for Swift (app.h) : (swift_name("initialize(reference:)") (swift_name("initialize(reference_:)”)
    y
    • 2
    • 1
  • k

    Karlo Lozovina

    03/26/2021, 2:54 PM
    Does the
    !!
    operator have any overhead, if the value is never
    null
    ? I'm guessing no, but still...
    z
    n
    +2
    • 5
    • 18
  • t

    TwoClocks

    03/26/2021, 6:32 PM
    kotlin's
    Duration
    has no
    .between()
    to get a duration between instances. which is fine... but once I include the
    java.time.Duration
    all the nice kotlin extension functions like
    Int.inSeconds
    can't be found. Am I just stuck w/ the java ones if I need
    between()
    ?
    l
    h
    r
    • 4
    • 15
  • h

    Harry B

    03/27/2021, 7:53 PM
    Hey! I get this error:
    2021-03-27 19:53:03.556 [DefaultDispatcher-worker-1] ERROR Application - Unhandled exception caught for CoroutineName(call-handler)
    kotlinx.coroutines.CoroutinesInternalError: Fatal exception in coroutines machinery for DispatchedContinuation[<http://Dispatchers.IO|Dispatchers.IO>, Continuation at io.ktor.server.engine.BaseApplicationResponse$respondWriteChannelContent$2$1.invokeSuspend(BaseApplicationResponse.kt:166)@4ed1ef02]. Please read KDoc to 'handleFatalException' method and report this incident to maintainers
    	at kotlinx.coroutines.DispatchedTask.handleFatalException$kotlinx_coroutines_core(DispatchedTask.kt:144)
    	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:115)
    	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
    	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
    	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
    Caused by: java.lang.NoClassDefFoundError: Could not initialize class kotlinx.coroutines.CompletedExceptionally
    	at kotlinx.coroutines.CompletionStateKt.toState(CompletionState.kt:16)
    	at kotlinx.coroutines.CompletionStateKt.toState$default(CompletionState.kt:13)
    	at kotlinx.coroutines.AbstractCoroutine.resumeWith(AbstractCoroutine.kt:111)
    	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:46)
    	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    	... 4 common frames omitted
    When i run this function:
    val ApplicationCall.accountPrincipal: AccountPrincipal? get() = authentication.principal<AccountPrincipal>()
    fun ApplicationCall.user(): Account? = transaction<Account?> {
        Account.find { (Accounts.id) eq accountPrincipal?.id }.firstOrNull()
    }
    • 1
    • 3
  • t

    TheMrCodes

    03/28/2021, 9:37 AM
    Can anyone explain this behavior to me? [Solved]
    r
    k
    • 3
    • 10
  • j

    jvmusin

    03/28/2021, 11:46 AM
    Hi! Kotlin documentation says it's better to omit
    @param
    and
    @return
    statements from documentation wherever it's possible and mention them explicitly in the description. Do you agree with it and do you really try to omit them or you still use a javadoc-like documentation?
    a
    c
    +4
    • 7
    • 25
  • e

    Eugen Martynov

    03/28/2021, 8:11 PM
    If I set language level 1.8 would lambda compile to invoke dynamic or it is still anonymous class? https://medium.com/@christian.c.carroll/exploring-kotlin-lambda-bytecode-8c2d15afd490
    a
    • 2
    • 1
  • z

    zsperske

    03/28/2021, 8:12 PM
    If
    extension methods
    just get converted to static methods by the compiler, how do they have access to private/internal fields of their parent class? Edit: Answered, they dont.
    d
    • 2
    • 2
  • l

    LastExceed

    03/29/2021, 6:22 AM
    how do I get the nth element of a sequence ?
    mySequence.take(n + 1).last()
    doesnt feel right to me
    a
    • 2
    • 2
  • m

    Mark Buikema

    03/29/2021, 10:30 AM
    I have an abstract class with a subclass. I want the subclass to define a property with type Class, but its implementation should be a subclass of
    Param
    . How do I define this?
    abstract class Params
    abstract class Parent {
        
        abstract val paramsClass: Class<????> // should be a class that extends Params
    
    }
    class Subclass : Parent() {
        
        override val paramsClass = MyParams::class.java
    
    }
    data class MyParams : Params()
    l
    d
    • 3
    • 3
  • u

    user

    03/29/2021, 2:03 PM
    Kotlin 1.5.0-M2 Released – Ensure Smooth Migration to Kotlin 1.5.0 Kotlin 1.5.0-M2 is the last milestone release for Kotlin 1.5.0, which is coming this spring. So this is the last chance to make sure that your projects will successfully work with Kotlin 1.5.0. Install 1.5.0-M2 If you migrate your projects now, you can save yourself time and energy in the future, when Kotlin 1.5.0 comes […]
    r
    • 1
    • 1
  • n

    Nthily

    03/29/2021, 2:06 PM
    How do I use jetpack compose to select images from my phone album to add to the user interface?
    c
    v
    • 3
    • 4
  • l

    Liad Mazor

    03/29/2021, 5:25 PM
    I was wondering if Kotlin desktop is robust/complete enough to write a full desktop (macOS/Windows) app with? I haven't seen many example projects online and the documentation is non-existent. Should I give it a go? if not, does anyone have any experience with electron with Kotlin Js?
    r
    c
    +2
    • 5
    • 11
  • k

    kevinherron

    03/29/2021, 8:24 PM
    Does this seem like a bug to anyone else? In a Java library the annotations were just switched from jsr305 to jetbrains. There's a getter method defined like this:
    /**
         * Get the value of the OutputArguments Property, if it exists.
         *
         * @return the value of the OutputArguments Property, if it exists.
         * @see MethodNodeProperties#OutputArguments
         */
        @Nullable
        public Argument[] getOutputArguments() {
            return getProperty(MethodNodeProperties.OutputArguments).orElse(null);
        }
    Now in some Kotlin code that uses this library it is inferring the type to be
    Array<Argument?>?
    instead of
    Array<Argument>?
    as it did previously. So now what was once:
    override fun getOutputArguments(): Array<Argument> = methodNode.outputArguments ?: emptyArray()
    now won't compile unless it's changed to something like this:
    override fun getOutputArguments(): Array<Argument> {
        val outputArguments: Array<Argument>? =
            methodNode.outputArguments as Array<Argument>?
    
        return outputArguments ?: emptyArray()
    }
    a
    • 2
    • 5
  • s

    seetha

    03/29/2021, 9:28 PM
    Hello, I am new to Arrow library. Have a question on
    arrow.fx.coroutines.Schedule
    . Is there a way to get the number of attempt in the Either.catch
    Either.catch{
    	retry(Schedule.exponential(250.milliseconds)) {
    		evalOn(IOPool) {
    			//do something
    	  		incrementMetricSuccess(attempt)   -------> want to increment metric with the attempt it got successful
    		}
    	}
    }.mapLeft {
    	incrementMetricSuccess(attempt)    -------> want to increment metric with the attempt to fail
    }
    k
    • 2
    • 1
  • h

    Hitender Pannu

    03/30/2021, 8:28 AM
    Has anyone started using Apple M1 for android development? how was your experience
    c
    • 2
    • 3
  • m

    Mark

    03/30/2021, 10:23 AM
    Confused why this doesn’t work:
    private fun interface MySam {
        fun invoke()
        
        companion object {
            operator fun invoke(randomArg: String) = MySam { }
        }
    }
    When invoking
    MySam("anything")
    we get:
    Exception in thread "main" java.lang.ClassCastException: MySam$Companion$invoke$1 cannot be cast to kotlin.jvm.functions.Function
    UPDATE: workaround is to instead declare as an extension function of the
    companion object
    :
    private operator fun MySam.Companion.invoke(randomArg: Int) = MySam { }
    UPDATE2: Another workaround is to change interface visibility to non-private, then it works. Is this expected behavior? Try it out here: https://pl.kotl.in/OxBHwZAn5
    k
    t
    • 3
    • 4
Powered by Linen
Title
m

Mark

03/30/2021, 10:23 AM
Confused why this doesn’t work:
private fun interface MySam {
    fun invoke()
    
    companion object {
        operator fun invoke(randomArg: String) = MySam { }
    }
}
When invoking
MySam("anything")
we get:
Exception in thread "main" java.lang.ClassCastException: MySam$Companion$invoke$1 cannot be cast to kotlin.jvm.functions.Function
UPDATE: workaround is to instead declare as an extension function of the
companion object
:
private operator fun MySam.Companion.invoke(randomArg: Int) = MySam { }
UPDATE2: Another workaround is to change interface visibility to non-private, then it works. Is this expected behavior? Try it out here: https://pl.kotl.in/OxBHwZAn5
k

kqr

03/30/2021, 10:38 AM
is the last parameter lambda?
m

Mark

03/30/2021, 10:39 AM
Not sure what you mean
k

kqr

03/30/2021, 10:57 AM
ignore me
t

Tomasz Krakowiak

03/30/2021, 7:53 PM
@Mark It's a compiler bug - https://youtrack.jetbrains.com/issue/KT-45444
👍 1
View count: 5