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

    Big Chungus

    11/26/2019, 12:39 PM
    Is there a way to tell a compiler to open all classes and methods for test compilations?
    s
    e
    m
    • 4
    • 9
  • n

    New111

    11/26/2019, 11:24 PM
    Hello all, what is the kotlin-native way to stop/kill another process ?
    m
    • 2
    • 1
  • c

    Colton Idle

    11/27/2019, 4:54 AM
    Kinda feel silly but I can't wrap my head around people using different functions to essentially just do a null check. I still find
    if (myItem != null) { //do something }
    makes sense in kotlin as it does in java. Is using
    let{}
    really needed? Would someone say that my if statement is not idiomatic? I like to follow the 90 day rule. If I come back to the code in 90 days... which one will I understand? I feel that most would choose the if.
    👍 2
    p
    m
    s
    • 4
    • 4
  • k

    KtNewbie

    11/27/2019, 7:15 AM
    Hello, I have tried to make JPA Entity classes for a Spring Boot - Data Rest project. I worked with data classes, but the Lazy loading not working with them (because they are final?). There is an another way to get toString and hashCode like lombok in java?
    n
    h
    • 3
    • 3
  • o

    obadz

    11/27/2019, 10:37 AM
    Newby question: why was kotlinx.serialization designed as a compiler plugin rather than an annotation processor?
    d
    r
    +2
    • 5
    • 18
  • j

    jk2018

    11/27/2019, 11:33 PM
    kotlinx.cli is now available ( see https://blog.jetbrains.com/kotlin/2019/11/kotlin-1-3-60-released/ ) .. Is there an example of how to add the dependency in a groovy build.gradle file? Or just add it as a maven/jcenter dependency?
    ➕ 3
    e
    d
    • 3
    • 3
  • c

    chervak.av

    11/28/2019, 7:51 PM
    newbie question! Hello! please tell me how can I add char to string?
    m
    k
    t
    • 4
    • 6
  • c

    chervak.av

    11/29/2019, 6:55 PM
    hello all! can i add var like pattern in Regex? something like
    var regWord = word.toRegex
    var list = line.split(Regex("""^(regWord)+"""))
    i need to count regWord in line
    k
    • 2
    • 5
  • k

    Ky Leggiero

    12/01/2019, 3:48 AM
    Is there a Kotlin/IDEA thing like Swift Package Manager?
    d
    s
    +2
    • 5
    • 9
  • a

    Arslan Mushtaq

    12/01/2019, 7:19 PM
    Hello everyone, I’m having a very strange issue. I cannot find BadgeDrawable in my project anywhere? Do I need to add a dependency for it?
    m
    • 2
    • 1
  • h

    Hoanghun5

    12/01/2019, 10:23 PM
    What book would you recommend to someone who has decent experience in Java but wants to learn Kotlin? I saw Bruce Eckel is writing a book but it’s not finished yet sadly.
    t
    e
    a
    • 4
    • 3
  • h

    Hullaballoonatic

    12/01/2019, 10:26 PM
    what is the most performant way to access erased types? here's an example where perhaps you want to access it:
    iterface Foo : Comparable<Bar> {
        override fun equals(other: Any?) = when (other) {
            is Comparable<*> -> // other is Comparable<Bar> && (other as Comparable<Bar>).compareTo(this) == 0
            else -> false
        }
    }
    cast as and try/catch?
    d
    k
    • 3
    • 6
  • s

    Steve

    12/01/2019, 11:53 PM
    Does anyone have a good boilerplate setup for solving Advent of Code problems with Kotlin?
    t
    s
    s
    • 4
    • 6
  • s

    Slackbot

    12/02/2019, 5:50 AM
    This message was deleted.
    s
    r
    • 3
    • 5
  • m

    mike_shysh

    12/02/2019, 1:57 PM
    Hi, Please help me to find out what is the best way to implement thread-safe singleton (for DB connection)? Here are the variants:
    object DBProvider {
        @Volatile private var dbSession: Session? = null
    
        fun getDBSession(): Session = dbSession ?: synchronized(this) {
            dbSession ?: when (dbType) {
                DBTypes.MYSQL.type -> MySqlSession(host = dbHost, port = dbPort).getSession()
                DBTypes.ORACLE.type -> OracleSession(host = dbHost, port = dbPort).getSession()
                else -> throw Exception("Unsupported DB type - $dbType.")
            }.also { dbSession = it }
        }
    ...
    d
    • 2
    • 23
  • a

    antoniomarin

    12/02/2019, 4:30 PM
    Hi all, I was wondering is there a better way to create
    set
    or
    distinct
    lists from a list of objects based on their property? Currently I’m looping through each user and adding them one by one to the
    set
    val userEmails = mutableSetOf<String>()
    users.forEach {
        userEmails.add("Adding unique email: ${it.email}")
    }
    print(userEmails)
    s
    s
    • 3
    • 10
  • d

    Damian

    12/02/2019, 6:21 PM
    Hi, I'm following the Udacity bootcamp and one of the examples in the lecture doesn't work for me, this is the code:
    package aquarium
    
    class Aquarium (var length: Int, var width: Int, var height: Int) {
    
        var volume: Int
            get() = width * height * length / 1000
            set(value) = {height = (value * 1000) / (width * length)}
    This is the warning I'm getting from Intellij for the set(value):
    Type mismatch: inferred type is () -> Unit but Unit was expected
    I don't understand what is this supposed to signify?
    r
    z
    • 3
    • 2
  • s

    Steve

    12/02/2019, 8:20 PM
    does Kotlin have some kind of index type? for example, I want to pass a List, and an index into that List. I could pass just an Int as the index, but it's possible that is outside the bounds of the list. I was wondering if there was some kind of type-safe way to tie the two together?
    🇳🇴 1
    🆗 1
    h
    l
    • 3
    • 5
  • b

    bbaldino

    12/02/2019, 8:57 PM
    I'm having some trouble testing a KClass<T> for being an Enum, and then getting an equivalent to
    Class<T Extends Enum<T>>
    out of it. for example:
    fun <T : Any>test(valueType: KClass<T>) {
        when (valueType) {
            Enum::class -> {
                // How to get 'x' to be Class<T> where T extends Enum<T> ?
                val x = valueType.java
            }
            else -> TODO()
        }
    }
    t
    d
    • 3
    • 14
  • o

    Oleh Ponomarenko

    12/03/2019, 8:21 AM
    Hello! How can I get IntRange of the indexes after slicing the array of bytes? I slice array in this way:
    val chunks = data.asIterable().chunked(CHUNK_SIZE)
    For example, I need an index (from original array) of first byte in second chunk.
    m
    • 2
    • 2
  • r

    Ruyi Li

    12/03/2019, 1:26 PM
    > kotlinc -script .\p2.kts
    error: invalid argument: -script
    info: use -help for more information
    Anyone know why this is happening? I'm on Windows and installed Kotlinc through the zip on the releases page, and when I run
    kotlinc -version
    it outputs
    > kotlinc -version
    info: kotlinc-native 1.3.60 (JRE 9.0.1+11)
    Kotlin/Native: 1.3.60
    -script is not listed in the options specified in -help.
    m
    r
    • 3
    • 6
  • v

    victor-mntl

    12/04/2019, 12:51 AM
    If I have a function that uses as first argument an instance of a class, can I use the dot notation with it? I mean, can I have something like:
    fun myFunction (foo :MyClass) { /.../ }
    and call it like:
    val foo = MyClass( /.../ )
    foo.myFunction()
    d
    • 2
    • 3
  • o

    Oya Canli

    12/05/2019, 1:26 PM
    Hi! In java, there is a shortcut for switching the value of a boolean, like this:
    myBoolean ^= true
    So if it was true, it becomes false and if it was false it becomes true. Is there an equivalent in kotlin?
    k
    d
    m
    • 4
    • 7
  • d

    df

    12/05/2019, 5:13 PM
    I'm sure there is an elegant way to convert this
    val catalogues = mapOf(
        "de-catalogue" to listOf(29L, 10010L, 10012L, 10013L),
        "fr-catalogue" to listOf(10007L, 10019L, 10020L),
        "nl-catalogue" to listOf(10008L, 10023L, 10024L),
        "it-catalogue" to listOf(10021L),
        "es-catalogue" to listOf(10022L)
    into a Map<Long,String> where each list value becomes the key and the key (from the original map) becomes the value
    k
    • 2
    • 9
  • h

    Harsh Mistry

    12/05/2019, 6:10 PM
    Which is the best way to getting started in the kotlin ?
    s
    • 2
    • 2
  • b

    bbaldino

    12/05/2019, 7:14 PM
    i have a class in a lib whose constructor is marked as
    internal
    , but when i include that lib (via a maven dependency) in a java project, i can still access that constructor. am i misunderstanding the scope of
    internal
    ?
    m
    • 2
    • 10
  • e

    Ellen Spertus

    12/05/2019, 11:49 PM
    I have some ugly code that I’d like to improve. My goal is to create an array
    results
    as long as the list
    neededPermissions
    where every element of
    results
    has the value
    PackageManager.PERMISSION_GRANTED
    except for a single element. Here’s my code:
    val results = neededPermissions.map { PackageManager.PERMISSION_GRANTED }.toIntArray()
    results[0] = PackageManager.PERMISSION_DENIED
    I know how to do what I want in Scheme (with
    cons
    and
    cdr
    ). What’s a nice way to do it in Kotlin?
    🦗 1
    s
    k
    • 3
    • 5
  • i

    Ive Vasiljevic

    12/06/2019, 8:54 AM
    By using delegating properties, first example is the same as the second example without using delegates.
    class User(private val map: MutableMap<String, String>) {
        
        val name: String by map
        val lastName: String by map
    }
    
    class User1(private val map: MutableMap<String, String>) {
        
        val name: String
        val lastName: String
        
        init {
            
            name = map["name"].toString()
            lastName = map["lastName"].toString()
        }
    }
    So basically, when accessing property "name" from class User in the fun main(). It is using MutableMaps default getValue() implementation to get the value?
    d
    k
    • 3
    • 5
  • o

    Oleh Ponomarenko

    12/06/2019, 2:23 PM
    Hello! How to use data from File in Kotlin and delete the information after? I get OutOfMemoryExcetion. I send data every 5 seconds from the File to the server. The data all the time is updated. Then need to remove the data. Now I have this :
    val bytes = fileOut.readBytes().sliceArray(range)
    And then I send the bytes. I do nothing with this after. As I understand JVM garbage collector should clean this data myself after a while but does it not always. I google this, I think I can use something like try-with-resources in Java -
    use
    . But this extension is unable for the Class. Do you have some advice for me? Thanks.
    k
    h
    • 3
    • 18
  • f

    Florian

    12/07/2019, 9:05 AM
    What naming convention do you use for a situation like this:
    m
    m
    • 3
    • 11
Powered by Linen
Title
f

Florian

12/07/2019, 9:05 AM
What naming convention do you use for a situation like this:
m

Milan Hruban

12/07/2019, 9:26 AM
I would keep this as it is. Also it might be better asking in #codingconventions
💯 2
f

Florian

12/07/2019, 12:15 PM
Sorry, next time
u then use the
this
keyword to access the property?
m

Mike

12/07/2019, 1:11 PM
This class will only have one property called name. In Java terms, the name field after User is just a constructor parameter and not visible anywhere else. To demonstrate, rename it to inName and try to access it on a constructed User.
f

Florian

12/07/2019, 4:09 PM
it's visible in an init block tho
where it uses the constructor param and not the property
m

Mike

12/07/2019, 4:27 PM
The
init
block is the constructor. So, in that case, you'd have to use
this
and it would refer to the property, name, and not the 'constructor parameter' name.
f

Florian

12/07/2019, 5:14 PM
Thanks
Also, there is no way to move this initialization logic into the constructor right?
the
toUpperCase
call
m

Mike

12/08/2019, 1:46 PM
If you mean inside the parenthesis, then no. It's just for property and default definitions. What you have will only occur at construction time, so it effectively is 'in the constructor'.
View count: 2