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

    Ivan Brko

    09/18/2021, 12:56 PM
    can anyone recommend any good kotlin books or resources for already experienced programmers? i don't want someone to teach me what is if/else, i would like to get a good overview of existing language features and patterns
    r
    c
    m
    • 4
    • 4
  • s

    Simas Butavičius

    09/19/2021, 10:36 AM
    EDIT: Answered in thread. Could someone please explain, why i can’t access anonymous object’s property, unless I declare val as private? Thank you for your time.
    class Demo {
        class Normal {
            val greeting = "I'm Normal class instance"
        }
        val normal = Normal()
    
        private val privateAnonymous = object {
            val greeting = "I'm anonymous class instance"
        }
        
        val anonymous = object {
            val greeting = "I'm also anonymous class instance"
        }
        
        val normalGreeting = normal.greeting // I'm Normal class instance
        val privateAnonymousGreeting = privateAnonymous.greeting // I'm anonymous class instance
        val anonymousGreeting = anonymous.greeting // Unresolved reference: greeting
    }
    e
    • 2
    • 2
  • e

    elect

    09/19/2021, 4:42 PM
    is there some nice small lib for dealing with byte dimensions (ie: MB, GB)?
    m
    • 2
    • 4
  • g

    Gilles Barbier

    09/19/2021, 9:09 PM
    Hello, I've spent so much time without managing to get any response: Given a
    Kfunction
    obtained from an expression such as
    obj::method
    where obj is an instance from a Class. How can I retrieve the underlying
    obj
    from the
    Kfunction
    ???
    s
    k
    b
    • 4
    • 10
  • u

    ursus

    09/20/2021, 1:22 AM
    If I have a rather large
    Map<String, String>
    (keyed labels of UI elements), which is created dynamically via fetching the labels from api -- so not statically with string literals. Does it make sense to implement a
    Trie
    or is this somehow optimized under the hood in jvm since
    String
    is so special? I remember faintly about string interning, but that only applies to string literals and deals with copies, right? It might be more memory efficient, however what about lookup? I believe there are native implementations of this inside when simply matching
    Strings
    , no? Also, turning unicode strings to char arrays won't work all that great?
    c
    d
    e
    • 4
    • 16
  • u

    ursus

    09/20/2021, 2:18 AM
    How do primitives work in kotlin?
    public class Char private constructor() : Comparable<Char> {
        public fun toInt(): Int
        ...
    }
    First of all, what is this even, and why does it compile? a concrete class with no implementation of methods? Secondly, does
    charArratOf('a', 'b', 'c')
    create 3 instances of Char class? Or, is there some magic
    e
    c
    • 3
    • 7
  • j

    Javier

    09/20/2021, 10:14 AM
    Is this the correct behavior? Only is working inside functions
    c
    r
    t
    • 4
    • 25
  • s

    Sam Marz

    09/20/2021, 3:21 PM
    hi, Is it possible to print the names of my custom colors within a list?
    j
    • 2
    • 9
  • p

    Paul Griffith

    09/20/2021, 6:08 PM
    Is there a way to have a data class secondary constructor provide a value for a non-primary-constructor
    val
    ? 🧵 ->
    j
    • 2
    • 9
  • u

    ursus

    09/21/2021, 12:42 AM
    Hi, If use a 3rd party library, like lets say moshi, and I create useful extensions, and useful columnadapters etc, and want to distribute this to other consumers (internally). How should I name this module? Is the X suffix common place in kotlin in user space as well?
    :moshix
    ? or more conservative
    :base-moshi
    ? (
    :sqdelightx
    ,
    :retrofitx
    etc) same goes for my custom
    Flow
    operators, since flow likes to keep it bare bones
    a
    j
    • 3
    • 8
  • m

    Michael Marshall

    09/21/2021, 5:33 PM
    What’s the best way to ensure at least one of two class constructor params is non-null at compile time? For example in
    data class Foo(val a: String? = null, val b String? = null)
    I could write
    data class Foo(val a: String? = null, val b String? = null)
    {
      init {
             requireNotNull(a ?: b)
           }
    }
    But this only causes a crash at runtime. How do I achieve the same result with compile time safety?
    j
    r
    +4
    • 7
    • 23
  • d

    Daniele B

    09/21/2021, 5:46 PM
    I have an array of unsigned Integers (from 0 to 255)
    val signerPrivateKey : IntArray = intArrayOf(6,199,39,185,82,199,26,124,50,54,50,128,200,204,220,164,48,77,49,31,9,228,77,61,123,53,62,86,163,183,9,172,101,133,107,31,215,181,167,87)
    how do I convert it to a ByteArray?
    p
    f
    +2
    • 5
    • 6
  • n

    Nathan Schwermann

    09/21/2021, 6:38 PM
    I want to bring kotlin support to a java library without adding kotlin to it. What I want is to make a sealed class. Is there any kind of meta data or naming conventions I can use to make my classes work as a sealed class when consumed by kotlin?
    :nope: 1
    j
    e
    • 3
    • 7
  • a

    Alejandro Rios

    09/21/2021, 7:30 PM
    Hello all, not sure if this is a noob question but here it goes: How can I get the difference between two List/ArrayList regardless of the order of the sentence? I mean, for example these two lists
    val first = listOf(1, 2, 3, 4, 5)
     val second = listOf(1, 2, 3)
    If I use
    first.minus(second)
    I’ll get
    [4, 5]
    but If I use
    second.minus(first)
    I’ll get
    []
    p
    j
    i
    • 4
    • 11
  • h

    herlevsen

    09/22/2021, 7:35 AM
    Hi all! Question that has probably been answered before, but I couldn’t find/understand those answers: Why do we need to annotate “value classes” with @JvmInline? Ie. why is it not implied that a “value class” should be inlined? And what is a “value class” without @JvmInline?
    j
    s
    • 3
    • 8
  • k

    Karlo Lozovina

    09/22/2021, 9:03 AM
    Is there a stdlib function like
    repeat()
    but that returns the result as a collection? to the effect like
    (0..i).map() { foo() }
    ?
    e
    c
    • 3
    • 3
  • h

    Hamza Ahmad

    09/22/2021, 9:15 AM
    Hello, Is there any kotlin library for Calendar that we want to use in CommonMain .......... like for java we use the same thing as 'Java.util.Calender'?
    k
    • 2
    • 2
  • j

    jeggy

    09/22/2021, 9:28 AM
    Are Jetbrains maintaining any Docker images? I'm looking for some easy and trusted way of getting access to
    kotlinc
    inside a Docker Image.
    c
    • 2
    • 7
  • m

    MarkRS

    09/22/2021, 9:34 AM
    Why does the KMM application type generate an Android module with a "java" directory rather than a "kotlin" one? I suppose the more important (?) question is, is there any reason not to rename it "kotlin"?
    e
    a
    • 3
    • 5
  • m

    MinaSamir

    09/22/2021, 9:55 AM
    Hi everyone, any recommendations for courses to learn kotlin from the start
    c
    s
    • 3
    • 3
  • s

    suhas

    09/22/2021, 12:04 PM
    Any good resource to read about comparator, comparables, sortedWith, compareBy? I want to sort objects based on multiple properties of object in custom ordering logic.
    i
    • 2
    • 1
  • s

    suhas

    09/22/2021, 1:11 PM
    How do I order ids based on some logical ranking, let's say I have IDs of 1,2,3,4,5. But I want to rank them in order of 3,4,2,1,5. Here Id 3 is most important category and should be ranked first. Ids are Int
    k
    j
    +2
    • 5
    • 9
  • i

    igor.wojda

    09/22/2021, 1:36 PM
    Imagine we have a websocket server that can send various message types (defined as strings). Now for each of these received messages we need to create instance of specific class. I was able to model this data using sealed interface and enum class:
    sealed interface WebSocketMessage {
        data class Hello(data: String):WebSocketMessage
        data class Bye(data: String):WebSocketMessage
    }
    
    enum class WebSocketMessageType(val type: String, val kotlinClass: KClass<out WebSocketMessage>) {
        HELLO("hello", WebSocketMessage.Hello::class),
        BYE("bye", WebSocketMessage.Bye::class),
    }
    
    // get message
    val webSocketMessageType = enumValues<WebSocketMessageType>().firstOrNull { it == type }
    ...
    I wonder if there is a way to model this using one entity, so adding the new messages types require change in a single place 🤔
    s
    t
    • 3
    • 2
  • t

    thanksforallthefish

    09/22/2021, 2:27 PM
    this is probably stupid, but I am not sure how to find an answer. in spring, there is a file defining:
    fun MockMvc.get(urlTemplate: String, vararg vars: Any?, dsl: MockHttpServletRequestDsl.() -> Unit = {})
    I defined my own version
    fun MockMvc.get(urlTemplate: String, vararg vars: Any?, subject: Subject = WithMockUser.defaultUser, dsl: MockHttpServletRequestDsl.() -> Unit = {})
    in a test, by mistake, I imported both extension function, but when doing
    mockMvc.get("/uri")
    the first one got called. I am curious, how is the order defined in this case? I thought it could be the order of imports, but I tried both combination and the result did not change:
    import org.springframework.test.web.servlet.get
    import my.own.get
    or
    import my.own.get
    import org.springframework.test.web.servlet.get
    made no difference
    c
    j
    • 3
    • 4
  • b

    Ben Tilford

    09/22/2021, 5:07 PM
    Is it possible to compose or extend annotations in kotlin? In java you could add an annotation as a property like
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE})
    public @interface SuperAnnotation {
        String value();
    }
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE})
    public @interface SubAnnotation {
        SuperAnnotation superAnnotation();
        String subValue();
    }
    h
    • 2
    • 3
  • s

    savrov

    09/22/2021, 11:05 PM
    hello, i tried to google, but did not find anything. a want to make a real long fun name for my unit test, but met an error (screenshot) It happens only with a really long name of fun. Can i overcome it somehow?
    j
    e
    +2
    • 5
    • 9
  • e

    enshahar

    09/23/2021, 1:42 AM
    Hi everyone, I tried to use 
    <http://kotlin.io|kotlin.io>.path.createTempDirectory()
     to create temporary directory on my kotlinc 1.4.31 but failed on Windows, WSL2 and Mac. In the Kotlin playground web,  the code raises `SecurityException`(which is correct) but all my systems (including kotlinc and intelliJ IDEA) cannot resolve the package 
    kotlin.io.path
     . Is there anything I need to do to use the 
    kotlin.io.path
     package?
    e
    • 2
    • 4
  • a

    Amol

    09/23/2021, 10:23 AM
    Question: How to check certain combinations of inputs in Kotlin I have a data class as below:
    data class foo(
      val a: T?,
      val b: U?,
      val c: V?,
      val d: X?
    )
    This is sent as an arg to a function
    bar(val foo: Foo)
    Now in this function
    bar
    , I want to allow only certain combinations of foo's members e.g.
    if(a!=null){
      // If a is input, nothing else is allowed
      if(b!=null || c!=null || d!= null) throw Exception()
    }
    if(b!=null){
      // If b is input, nothing else is allowed
      if(a!=null || c!=null || d!= null) throw Exception()
    }
    if(c!=null){
     // If c is input, d is allowed, a and b not allowed
       if(a!=null || b!=null ) throw Exception()
    }
    Obviously, more the args, the worse it gets. What is a cleaner way of doing this?
    j
    • 2
    • 3
  • e

    elect

    09/23/2021, 11:43 AM
    Writing a dsl, the getters aren't supposed to be used, so I'm writing this at the moment:
    var maxGCPauseMillis: Int
                get() = error("invalid")
                set(value) ..
    does anyone have a better solution?
    r
    j
    • 3
    • 8
  • b

    Brian Donovan

    09/23/2021, 4:07 PM
    Hey I’m new to Kotlin and wasn’t sure where to ask this question. What is interoperability between Java and Kotlin. Thanks
    p
    • 2
    • 3
Powered by Linen
Title
b

Brian Donovan

09/23/2021, 4:07 PM
Hey I’m new to Kotlin and wasn’t sure where to ask this question. What is interoperability between Java and Kotlin. Thanks
p

Paul Griffith

09/23/2021, 4:08 PM
https://kotlinlang.org/docs/java-interop.html
Or the other way around, https://kotlinlang.org/docs/java-to-kotlin-interop.html
b

Brian Donovan

09/23/2021, 4:09 PM
thanks!
View count: 6