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

    zak.taccardi

    11/03/2022, 3:36 AM
    How do I access the delegating instance when using delegated inheritance. Is it possible?
    interface Validatable {
        fun validate()
    }
    
    class Impl() :
        // both these extend `Validatable`
        Validatable1 by Validatable1.Impl(),
        Validatable2 by Validatable2.Impl(),
        Validatable {
    
        override fun validate() {
            // how do I call:
            // validatable1.validate()
            // validatable2.validate()
            
            // or bonus - can I access the `Validatable1.Impl()` instance at all?
        }
    }
    e
    a
    • 3
    • 3
  • s

    Slackbot

    11/03/2022, 12:23 PM
    This message was deleted.
    t
    p
    • 3
    • 2
  • p

    Pasha Finkelshteyn

    11/04/2022, 10:49 AM
    Heya folks! My friend and I are streaming how he learns to write in Kotlin and I learn GameDev: https://twitter.com/asm0di0/status/1588103011590610946 In ≈10 minutes!
  • r

    Ruckus

    11/04/2022, 3:49 PM
    Is there an easy way to stop any stdlib functions from being imported automatically? I just got bit again when I accidentally used
    value.toString()
    instead of
    value?.toString()
    . I'm not a fan of
    Any?.toString()
    , and I'd like to just get rid of it locally if possible.
    e
    • 2
    • 5
  • e

    elect

    11/05/2022, 4:49 AM
    trying to use
    sealed interface
    , Idea's popup says
    The feature "sealed interfaces" is only available since language version 1.5
    then I click it and in my
    build.gradle.kts
    it adds
    val compileKotlin: KotlinCompile by tasks
    compileKotlin.kotlinOptions {
        languageVersion = "1.5"
    }
    but
    sealed
    is still marked as error and compiling fails:
    > Task :buildSrc:compileKotlin FAILED
    3 actionable tasks: 1 executed, 2 up-to-date
    e: /home/elect/IdeaProjects/vkk/buildSrc/src/main/kotlin/vkk/parsing.kt: (79, 1): The feature "sealed interfaces" is only available since language version 1.5
    e
    • 2
    • 5
  • o

    Oleg Shuliak

    11/05/2022, 10:42 AM
    hey everyone. I’ve got a question about interfaces. I can’t yet understand the best way of how to decide which concrete implementation of interface to use. Let’s imagine, that I have
    ServiceInterface
    that has 2 implementations
    ConcreteService1
    and
    ConcreteService2
    It’ll have one function
    doWork()
    . I need to use one implementation or another based on some property, that comes as a parameter. And I don’t understand where do I resolve which concrete class to use.
    class SomeClass(
        val someService: ServiceInterface
    ) {
        fun someFunction(status: String) {
            when(status) {
                "ACTIVE" -> someService.doWork() // or even better to return the instance of service
                "INACTIVE" -> someService.doWork()
            }
        }
    }
    Could someone give a hint?
    a
    p
    • 3
    • 4
  • m

    Martin Gaens

    11/05/2022, 11:28 AM
    I'm trying to get started writing my own full-stack applications in Kotlin, however, I'm not sure how to properly set up live reloading. Basically, I'd like to have a Kotlin/JVM backend and a Kotlin/JS frontend. I'd like the JVM server to serve all the files and the JS frontend to compile into JS to be run in the browser. Is there a way to enable live reloading in such a setup?
    r
    • 2
    • 2
  • e

    elect

    11/06/2022, 9:40 AM
    instantiating a class, there is a field
    comment
    which I'm initializing by delegation
    sealed class Type(line: String) {
        val comment by line
    However there might be some cases where I need to set it explicitly via constructor.. idiomatic code
    sealed class Type(line: String, val comment: String = by line)
    what's my best option for this?
    s
    e
    i
    • 4
    • 7
  • m

    Muhammad Usman

    11/07/2022, 5:34 AM
    Hi, How to figure out this compiler error?
    Type parameter output is declared as 'out' but occurs in 'invariant' position in type Flow<PagingData<output>>
    
    abstract class PaginatedFlowUseCase<in Input, out output>(
        private val dispatcher: CoroutineDispatcher
    ) {
        operator fun invoke(input: Input): Flow<PagingData<output>> {
            return execute(input).flowOn(dispatcher)
        }
    
        protected abstract fun execute(input: Input): Flow<PagingData<output>>
    }
    But it works when changing PagingData to kolin.Result class
    y
    s
    • 3
    • 4
  • r

    Rohan Sanap

    11/07/2022, 8:01 AM
    In swift, we can confirm to any protocol / interface using extensions. Can we add interface conformance to certain class using extension in Kotlin?
    g
    s
    • 3
    • 3
  • l

    Lukasz Kalnik

    11/07/2022, 9:35 AM
    Somehow all of my tests stopped seeing
    internal
    members of the tested classes (even though they are in the same Gradle module). Generally I made some changes which currently broke the build, but they are not related to the internal function/properties. So the project indeed should not build, but the error message is definitely a false positive.
    y
    e
    • 3
    • 6
  • z

    Zinedine Bedrani

    11/07/2022, 12:33 PM
    HI, I saw in some projects for handling dependencies something like that
    object Libs {
    object Google {
    …
    object Test {
    ……
    }
    object Firebase {
    …..
    }
    }
    object Accompanist {
    ……
    }
    object Gson {
    …..
    }
    object Log {
    …….
    }
    //other objects ...
    }
    Is it ok to creates many object like this just to handle dependencies ? for me it’s not :(
    j
    v
    e
    • 4
    • 16
  • e

    elect

    11/07/2022, 1:16 PM
    I just got to know that
    Contracts are not allowed for operator functions
    Why is that?
    • 1
    • 1
  • y

    y

    11/07/2022, 2:07 PM
    is it idiomatic to use
    T?
    like an optional of type
    T
    ?
    j
    k
    • 3
    • 8
  • r

    Rodrigo Silva

    11/07/2022, 2:09 PM
    Hello all, I'm trying to run the tests, but it's giving the following error.
    Cannot inline bytecode built with JVM target 17 into bytecode that is being built with JVM target 1.8. Please specify proper '-jvm-target' option
    my config
    tasks {
        test { useJUnitPlatform() }
        compileKotlin { kotlinOptions.jvmTarget = "17" }
        ...
    }
    What am I doing wrong?
    e
    • 2
    • 4
  • e

    Ellen Spertus

    11/07/2022, 2:42 PM
    Why is the second argument to
    require()
    a function rather than a string? I can think of two possible answers: 1. In case constructing the message is expensive (seems unlikely). 2. In case we want to do additional processing before throwing the exception, such as logging or cleaning up. I'm teaching about Kotlin exceptions, so I really want to get this right.
    c
    j
    +2
    • 5
    • 13
  • e

    Ellen Spertus

    11/07/2022, 4:04 PM
    I have the following property declaration in a companion object:
    class WordleGame(val secretWord: String) {
        companion object {
            private val words = java.io.File("words.txt").readLines()
    
            fun playGame() {
                val game = WordleGame(words.random())
                ...
            }
        }
    }
    
    fun main() {
        WordleGame.playGame() // ExceptionInInitializerError
    }
    Is there a clean way to catch a
    FileNotFoundException
    ? I can catch a
    ExceptionInInitializerError
    in
    main()
    and pull out its cause, but I'm hoping for something easier to explain to students, possibly restructuring the code.
    c
    e
    +3
    • 6
    • 13
  • e

    elect

    11/08/2022, 4:07 AM
    is there a way I can define a
    NULL
    as a companion object of an inline class using a type parameter?
    @JvmInline
    value class Ptr<T>(val adr: Adr = 0L) {
        companion object {
            val NULL: Ptr<*>
                get() = Ptr(MemoryUtil.NULL) // Not enough information to infer type variable T
        }
    }
    g
    e
    • 3
    • 10
  • m

    Michael de Kaste

    11/09/2022, 10:48 AM
    fun main() {
        println("%s %s".format("hi", "bye"))
        println("%s %s".format(*arrayOf("hi", "bye")))
        println("%s %s".format(arrayOf("hi", "bye"))) // java.util.MissingFormatArgumentException: Format specifier '%s'
    }
    Anyone know why it goes wrong with a pure array declaration?
    e
    r
    • 3
    • 4
  • x

    Xad Kile

    11/09/2022, 12:51 PM
    I am having an issue related to object declaration (something like
    object MyObject{ }
    ). In my app, there's a snippet that looks like this
    fun myFunction():Any{
        try{
            // do things
        }catch(e:Throwable){
            return MyObject.sideEffect()
        }
    }
    
    object MyObject{
        fun sideEffect():Any{
            //....
        }
    }
    the code inside the try block will throw an StackOverflowError under certain condition. The StackOverflowError is caught, and a side effect is emitted. This side effect is produced by an object declared in a different file, and half of the time, it will throw this exception; while on the other half, it runs just fine.
    Could not initialize class com.example.MyObject
    java.lang.NoClassDefFoundError: Could not initialize class com.example.MyObject
    However, if I run this
    val mo = MyObject
    before calling
    myFunction()
    , the
    NoClassDefFoundError
    exception is never thrown. Maybe this has something to do with the fact that MyObject is lazily allocated according to the official document. Could someone point me to a more in-depth document on object declaration? I need to know what is going on badly :melting_face: Thank you.
    e
    r
    j
    • 4
    • 9
  • x

    xun su

    11/09/2022, 9:27 PM
    Hello, I'm new to kotlin and I wanna know is there any SDK for kotlin ? I'm using inteliij IDEA, as you can see, there is a JDK but not a SDK for kotlin. and I also wanna whether I should download some kotlin-ish thing with
    apt
    ? I'm using ubuntu
    l
    a
    k
    • 4
    • 6
  • x

    xun su

    11/09/2022, 9:27 PM
  • a

    Alex

    11/10/2022, 9:18 AM
    Unable to add type when declaring a list of strings 1. i'm not sure if i'm doing something wrong, i recall being able to declare a list type to be string with the following code below
    val nameList:List<String>=listOf("Apple","Orange","Pear")
    ->> CODE A 2. I get the following error below "Property getter or setter expected" 3. i had to write as following
    val nameList=listOf<String>("Apple","Orange","Pear")
    which is fine with me, but why cant i use Code A, hope someone can advise me
    k
    • 2
    • 2
  • e

    elect

    11/10/2022, 10:24 AM
    isn't possible to add an extension on a inline class companion?
    j
    • 2
    • 2
  • y

    y

    11/10/2022, 12:41 PM
    I have a
    sealed class
    with many
    data class
    es that subclass it. I get these subclasses from some stream I want to build some sort of state machine that changes its state based on the last seen subclass. what’s a cheap/easy way to encode/decode the type of the seen class?
  • y

    y

    11/10/2022, 12:43 PM
    basically serialize/deserialize just the class kind, I don’t care about the state of the class itself
    m
    s
    • 3
    • 17
  • s

    sarvagya agarwal

    11/10/2022, 4:32 PM
    What's the best way to shorten this code ? All call() methods take and return a list. Is there a way to chain all these operations ?
    var list = serviceA.call(list)
    list = serviceB.call(list)
    list = serviceC.call(list)
    list = serviceD.call(list)
    k
    c
    +3
    • 6
    • 13
  • j

    jeggy

    11/10/2022, 5:39 PM
    How do I read an exception like this? Line 69 doesn't exists and line 10 is just the constructor
    java.lang.NullPointerException: null cannot be cast to non-null type kotlin.Number
    	at com.apurebase.puredynamic.repository.user.mapping.UserMapping.<init>(UserMapping.kt:69) ~[main/:?]
    	at com.apurebase.puredynamic.repository.user.mapping.UserMapping.<init>(UserMapping.kt:10) ~[main/:?]
    j
    a
    c
    • 4
    • 9
  • p

    PHondogo

    11/10/2022, 8:06 PM
    Hello! How to make Kotlin compiler issue an error when package name is not matching directory path?
    e
    • 2
    • 1
  • x

    xun su

    11/10/2022, 8:39 PM
    hi, I'm stuck with a weird problem. as you can see, I used IDEA to create a new project with gradle to learn kotlin if I add the line
    package com.xun.kotlin
    to the file, notice the error beside the build button. what's wrong with that ? if I comment the line, the error disappear. I used to be a frontend developer, In javascript, there is no need to add the line like this.
    e
    s
    • 3
    • 16
Powered by Linen
Title
x

xun su

11/10/2022, 8:39 PM
hi, I'm stuck with a weird problem. as you can see, I used IDEA to create a new project with gradle to learn kotlin if I add the line
package com.xun.kotlin
to the file, notice the error beside the build button. what's wrong with that ? if I comment the line, the error disappear. I used to be a frontend developer, In javascript, there is no need to add the line like this.
e

ephemient

11/10/2022, 8:44 PM
The reference to
MainKt
was to the package-less name. Now that you've added a package name, that needs to change.
You can either edit the run configuration or remove it and use the "run" action again, which will recreate the run configuration
x

xun su

11/10/2022, 8:59 PM
Hi, why you say
MainKt
, but not
Main.kt
? anyway I removed that line, Yes, now I could build and run the code via IDEA but how about use command line ?
java -jar path/to/build/libs/result.jar
just show me a error: then I searched a similar question and get a answer like this so I add a line to my
build.gradle.kts
,:
tasks.withType<Jar> { manifest { attributes["Main-Class"] = "com.xun.kotlin.MainKt" } }
but I got a another error:
xun@xun-Yoga-14sIHU-2021:~/Desktop/kotlin-basic/build/libs$ java -jar kotlin-basic-1.0-SNAPSHOT.jar 
Error: Could not find or load main class com.xun.kotlin.MainKt
Caused by: java.lang.ClassNotFoundException: com.xun.kotlin.MainKt
anyway, I just wanna run the project with the command line, what is wrong?
I mean, we can use IDEA to run the project, but I'd prefer to use command line
e

ephemient

11/10/2022, 9:01 PM
Kotlin wraps top-level elements of
file.kt
in a
FileKt
class for Java compatibility by default (you can choose a different name with
@file:JVM name("...")
)
to run from the command line, it would be better to use the Gradle application plugin. running as an individual jar like that will result in missing dependencies
plugins {
    application
}

application {
    mainClass.set("com.xun.kotlin.MainKt")
}
this will allow you to use
./gradlew run
x

xun su

11/10/2022, 9:06 PM
I thought the file
kotlin-basic-1.0-SNAPSHOT.jar
is in build directory so it has all it's dependencies bundled
e

ephemient

11/10/2022, 9:06 PM
or
./gradlew installDist
which will create a directory
build/install
containing everything needed, or
./gradlew distZip
or
./gradlew distTar
which will create that bundle in
build/distributions
no, dependencies are not bundled in the jar
x

xun su

11/10/2022, 9:08 PM
thank you , I've never learn java before so I just code like javascript way😄. thanks again
but I really wanna know why the solution I mentioned didn't get work in my project😀
s

Stephan Schroeder

11/11/2022, 8:56 AM
if you want all dependencies to be included into the jar - a so called "fat jar" - you can use the shadow-plugin: https://plugins.gradle.org/plugin/com.github.johnrengelman.shadow
e

ephemient

11/11/2022, 9:00 AM
you can but don't. https://product.hubspot.com/blog/the-fault-in-our-jars-why-we-stopped-building-fat-jars
x

xun su

11/11/2022, 10:00 AM
Hi, actually I'm follow the graalvm doc(https://www.graalvm.org/22.3/guides/#run-java-applications-on-graalvm-from-the-cli) , it says "If your Java project is built with Gradle, run
./gradlew build
to build the project and then run it from a JAR file as usual (
java -jar <JAR file>
)." I thought the builded jar file is in
build/libs/
, so I went there but still got error:
View count: 12