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

    Landry Norris

    08/02/2022, 6:30 PM
    yield
    is a suspend function, so it can only be called within a suspend function or other coroutine context.
    inner
    is not marked as suspend, so it can’t call suspend functions.
    m
    e
    • 3
    • 6
  • b

    Byeol

    08/03/2022, 11:14 AM
    Why kotlin default modifier is public?
    a
    r
    +2
    • 5
    • 6
  • r

    Romão

    08/03/2022, 9:09 PM
    Hello,
  • r

    Romão

    08/03/2022, 9:13 PM
    I'm learning Android development, trying to do code a simple app. Want to load a JSON file on the assets folder into a string in ViewModel (livedata). Can someone point correct way to load the JSON data (user, id:Int + name:String), shall i use GSON (looks its "old), Moshi (newer) or something else?
    j
    l
    a
    • 4
    • 3
  • t

    tseisel

    08/05/2022, 8:07 PM
    How do you format your Kotlin code? Do you use the IDE format action before committing, or do you rely on a Git hook to run an external tool, such as ktlint or ktmft ? I'm also a TypeScript developer and I'm very satisfied with
    prettier
    , which IMHO formats code in a cleaner way than those 2 Kotlin tools. ktlint looks promising, but I don't like that it also lint-checks code ; I'd expect it to focus on formatting. Any Kotlin alternative?
    l
    t
    +2
    • 5
    • 7
  • m

    martmists

    08/06/2022, 4:10 AM
    Using the
    application
    gradle plugin, how do I stop an application? The stop button is greyed out... If I close the tab, it simply keeps running in the background
    v
    • 2
    • 2
  • c

    Colton Idle

    08/06/2022, 5:34 AM
    I'm trying to de-dupelicate some Flow code. I basically have this method repeated pretty much identically for a bunch of different firestore queries. Is there a way to wrap this up so I don't have to do all of this cermoney for each firestore query I write?
    fun getBooks(): Flow<List<Book>> {
      return callbackFlow {
        val listener =
          FirebaseFirestore.getInstance().collection("books").addSnapshotListener { value, error -> trySend(value to error) }
        awaitClose { listener.remove() }
      }
      .doSomethingWithNullValueAndError()
      .conflate()
      .map { (value, _) -> 
        value.toObjects()
      }
      .flowOn(defaultDispatcher)
    j
    • 2
    • 4
  • r

    rednifre

    08/06/2022, 1:03 PM
    Heyo! Inspired by ArrowKt’s monad comprehensions, I wanted to implement one for Kotlin’s nullable types. The problem is that I don’t really understand functional interfaces. My goal: Have a
    bind
    extension function on all nullable types, that is only available inside of a
    nullable
    block. I tried to do it like this, but the
    bind
    function is not reachable. What’s the proper way to do this?
    class BindNullableException : IllegalAccessException()
    
    fun interface NullableBlock<A> : () -> A {
        fun <A> A?.bind() = this ?: throw BindNullableException()
    }
    
    fun <A> nullable(block: NullableBlock<A>): A? =
        try {
            block()
        } catch (e: BindNullableException) {
            null
        }
    
    fun main() {
    
        val a = getNullableA().bind() // should not work
    
        val nullableC = nullable {
            val a = getNullableA().bind() // should work
            val b = getNullableB().bind()
            getNullableC(a, b)
        }
    }
    
    fun getNullableA(): String? = null
    fun getNullableB(): String? = null
    fun getNullableC(a: String, b: String): String? = null
    t
    • 2
    • 4
  • l

    Lokik Soni

    08/06/2022, 3:45 PM
    Inside batteryProfile flow I am collecting alertLevel flow. batteryProfile flow emit value when there is change in device battery using broadcast and alertLevel emit value when I change in seekbar in UI. What is happening in my case is that When I change the alertLevel using seek bar and currently there is no emission in the batteryProfile then it also calls lambda and the whole block of code is called again and again. But according to me it should update the level variable when there is another emission in batteryProfile.
    batteryProfile(Unit).flowWithLifecycle(lifecycle).collect { result ->
       val level = alertLevel(Unit).firstOrNull()?.data ?: Constants.DEF_VAL_LEVEL
       
    }
  • a

    Ayfri

    08/06/2022, 11:53 PM
    Hi, isn't there a way to create a new gradle Kotlin module in Intellij ? I just can create a Java/Groovy/JavaScript module, or HTML/Compose/Selenium/Maven and Selenium has actually a
    Kotlin
    module option, but else I can't find how to create a new empty Kotlin module with gradle 🤔
    c
    v
    • 3
    • 3
  • a

    Abdullah Samir

    08/07/2022, 2:37 PM
    Hello, please i am new to Kotlin and i need to know the difference between Kotlin for android and Kotlin native (embedded and ios)
  • a

    Abdullah Samir

    08/07/2022, 2:38 PM
    Is there an JVM in kotlin for android and in native no JVM or what?
    v
    a
    l
    • 4
    • 4
  • e

    ephemient

    08/07/2022, 7:01 PM
    https://youtrack.jetbrains.com/issue/IDEA-118832 not a kotlin issue
  • m

    Muhammad Talha

    08/08/2022, 5:37 AM
    Hi all! Trying to get around my head on when to create stand alone functions vs classes with methods. It makes sense to me to make classes when there's some state that needs to be mutated. However, what about just some injected dependencies that don't change? In these cases should I just use a higher order function. Or would a class be better? Thanks!
  • j

    janvladimirmostert

    08/08/2022, 10:28 AM
    I'm trying to find a way to model
    query<Int, String>(sql: String)
    so that it will output
    O2<Int, String>
    since it has two output types or if it's
    query<Int, Int, Int>
    outputting
    O3<Int, Int, Int>
    etc or
    query<T1,T2,...,T99>(sql: String)
    should return
    O99<T1,T2,...,T99>
    Alternatively,
    query(O(Int, String)
    should output
    O<Int, String>
    How would you go about designing such an API? I've tried a few things which I've posted on SO, I've implemented the "alternatively" part, but ran into the problem where I'm outputting
    O2<Int.Companion, String.Companion>
    instead of
    O2<Int, String>
    which I could probably solve by doing
    query(O(InstanceOfInt, InstanceOfString)
    , but that already looks terrible. https://stackoverflow.com/questions/73271850/make-kotlin-function-output-tnk1-kn-when-the-input-is-tnk1-companion-kn-com
  • d

    David Smith

    08/09/2022, 9:23 AM
    is there a compiler flag or something I can set to make sure that an expression that is supposed to return
    Unit
    has to return
    Unit
    ? By being able to return anything when a
    Unit
    is expected I have created a bug in my code where some piece of side-effecting code wasn’t “run” to return
    Unit
    but the compiler didn’t pick it up because you can return anything if
    Unit
    is expected. 😞
    s
    • 2
    • 14
  • t

    thanksforallthefish

    08/09/2022, 12:34 PM
    hello, am I right in that when using java 17 with kotlin 1.7, java sealed classes are used? reason I am asking is because of https://github.com/mockk/mockk/issues/832, so I was curious to know if there is a compiler flag to disable the usage of java sealed classes, as clearly the compiler itself can do it (when using java 11 and kotlin 1.7, java sealed classes are not used ofc)
  • r

    Ryan Smith

    08/10/2022, 12:36 AM
    Is there a best practice for when statements where the
    else
    is there to be exhaustive, but is a
    no-op
    ? e.g.
    when {
        thing is OneThing -> // do something
        thing is SomethingElse -> // do something else
        else -> { /* no-op */ }
    }
    It doesn't exactly fit this case from the style guide especially since the app is still under development and there could be more cases:
    Prefer using
    if
    for binary conditions instead of
    when
    Is a bare
    return
    better? Or just sticking with
    no-op
    ? Personal preference?
    c
    e
    t
    • 4
    • 7
  • p

    phldavies

    08/10/2022, 9:19 AM
    I’m surprised there’s no guidance on when to prefer
    x?.let { ... }
    to
    if (x != null) { … }
    in the coding conventions. Am I right in thinking the preference of
    ?.let
    would be when the result is used as an expression, but
    if (!= null)
    is better served for control-flow?
    k
    r
    +2
    • 5
    • 4
  • b

    Ben Edwards

    08/10/2022, 7:36 PM
    Just starting my Kotlin journey. don't 80 days of the 100 Days of Code python course and my background is Oracle (mainly PL/SQL) and general Linux admin/WordPress. Doing the JetBrains Academy Basic Kotlin at the moment but thinking of doing https://www.udemy.com/course/android-oreo-kotlin-app-masterclass/ after that. Does this seem like a good way to go?
    j
    • 2
    • 6
  • p

    poohbar

    08/10/2022, 9:47 PM
    Question about Kotlin vs Java generics: this compiles just fine in Kotlin
    open class Animal<T1, T2>
    
    class Cat<I> : Animal<I, List<I>>()
    
    val x: Animal<String, List<String>> = Cat()
    however trying to do the same instantiation in java fails:
    Animal<String, List<String>> x = new Cat<String>() // error
    Is there something I can do to improve the generics in the Kotlin code so that they can be used from Java just like from Kotlin?
    e
    • 2
    • 3
  • s

    Stefan Oltmann

    08/11/2022, 9:17 AM
    Regarding KotlinConf: I don't find any information at what time the event starts and ends on each day. Is it like 8am to 8pm or only afternoon?
  • b

    Ben Edwards

    08/11/2022, 10:33 AM
    Hi, I am doing the JetBrains beginners tutorial but it's like pulling teeth. Wondering if there are any better beginner tutorials. Something video-based with lots of exercises ideally. Something fun 🙂. I don't mind paying a bit.
    j
    • 2
    • 2
  • b

    Ben Edwards

    08/11/2022, 10:36 AM
    I also got https://www.udemy.com/course/android-oreo-kotlin-app-masterclass/ which I am planning on doing next, or is there a better next one I should do? The multiplatform is very appealing but not sure how well it works if I wanted to make Android/iOS apps.
  • j

    juh juh

    08/11/2022, 11:32 AM
    What are my options if I want embedded scripting language for my kotlin multiplayform game? I despise LUA from the very depths of my soul, so it would be the last option I would be looking into
    r
    a
    • 3
    • 4
  • h

    hfhbd

    08/11/2022, 12:53 PM
    I want to generate Kotlin code from another source. At the moment I have my own representation and use KotlinPoet. This works fine, but I want to improve the code, eg
    !(foo == "FOO")
    should refactored into this
    foo != "FOO"
    . Is it possible to use the Kotlin plugin/frontend and its Kotlin fixup automatically? (I know this would require mapping my internal representation to Kotlin frontend code) Or do you know some other library which has basic optimizations? Alternative I have to write these Kotlin optimization by myself
    c
    • 2
    • 5
  • r

    rednifre

    08/11/2022, 1:12 PM
    Are there any technical reasons why inside of (), line breaks can’t imply commas, similar how inside {}, line breaks imply semicolons?
    v
    e
    • 3
    • 11
  • c

    clark

    08/11/2022, 2:53 PM
    Hi everyone, I am trying to figure out how to use Kotlin annotations and want to be able to annotate a function with a default error message that I can then use within the function. How do I access that error message?
    @Target(AnnotationTarget.FUNCTION)
    annotation class DefaultErrorMessage(val defaultErrorMessage: String)
    
    @DefaultErrorMessage("This is a test")
    fun testErrorMessage() {
      // How do I access the DefaultErrorMessage?
    }
    Also, would it be possible to access that message from a function called by the annotated function for example:
    @Target(AnnotationTarget.FUNCTION)
    annotation class DefaultErrorMessage(val defaultErrorMessage: String)
    
    @DefaultErrorMessage("This is a test")
    fun testErrorMessage() {
        testNestedAccess()
    }
    
    fun testNestedAccess() {
     // How do I access default error message?
    }
  • o

    oday

    08/11/2022, 2:56 PM
    how can I express,
    if the values in this list are valid values in my enum
    ? I am doing this
    if (queryParams.containsAll(GiveConsent.ConsentType.values())){
    but i get this error that it expects a collection and I gave it an Array
    j
    • 2
    • 6
  • b

    Ben Edwards

    08/11/2022, 3:10 PM
    Doing JetBrains Kotlin Basics cause and when I do this
    val arranged: Boolean = ((h1 >= h2 && h2 >= h3) || (h1 <= h2 && h2 <= h3))
    I get effectively marked down for adding the brackets for readability. So is this really affecting performance negatively? I'm a big fan of readability 🙂 Am I missing something?.
    c
    m
    +3
    • 6
    • 11
Powered by Linen
Title
b

Ben Edwards

08/11/2022, 3:10 PM
Doing JetBrains Kotlin Basics cause and when I do this
val arranged: Boolean = ((h1 >= h2 && h2 >= h3) || (h1 <= h2 && h2 <= h3))
I get effectively marked down for adding the brackets for readability. So is this really affecting performance negatively? I'm a big fan of readability 🙂 Am I missing something?.
c

Chris Lee

08/11/2022, 3:16 PM
Apparently you are trying to accomplish something that hasn’t been disclosed… what’s the problem / question here?
m

Michael de Kaste

08/11/2022, 3:17 PM
adding the outer brackets, to me, doesn't really add to any readability. But it doesn't matter at all. In fact, if you then want to do something with that result inlined, you would need to do it anyways.
((h1 >= h2 && h2 >= h3) || (h1 <= h2 && h2 <= h3)).let(::println)
c

Casey Brooks

08/11/2022, 3:19 PM
it shouldn’t affect performance, but the outer brackets do add unnecessary noise making it harder to read. I would personally omit those ones, giving you
val arranged: Boolean = (h1 >= h2 && h2 >= h3) || (h1 <= h2 && h2 <= h3)
which I think makes it more readable than having them there the
&&
operator has higher precedence than
||
so the inner parentheses are technically unnecessary, but I find it can help with readability, especially for folks that aren’t comfortable with operator precedence. So I would personally keep those ones in this expression
b

Ben Edwards

08/11/2022, 3:23 PM
@Casey Brooks exactly. I now get the outer () are not needed but the inner ones add clarity.
@Chris Lee that h1, h2, and h3 are either ascending or descending. So now i know the outer () should probably be missed out but the inner ones do add clarity.
v

Vampire

08/11/2022, 4:41 PM
I'd probably even do
val arranged: Boolean = ((h1 >= h2) && (h2 >= h3)) || ((h1 <= h2) && (h2 <= h3))
That's also what the "add clarifying parentheses" in Java code does, and what it also does in Kotlin now iirc.
b

Ben Edwards

08/11/2022, 4:44 PM
@Björn Kechel OK, how do the does (( )) add clarification?
v

Vampire

08/11/2022, 4:50 PM
Wrong Björn K. you pinged. 😉 While the precedence between
<=
and
&&
is easier to remember or deduct, you still have to remember it and also first read half of the line to understand the expression. With my / IntelliJs variant, it is instantly obvious what the sub-expressions are and you can just read it from left to right and right away understand it. It is simply simpler to grasp and understand and thus reduces brain-load.
Besides that I would probably (depending on the types of hX, I'd write
val arranged: Boolean = (h2 in (h3..h1)) || (h2 in (h1..h3))
r

Roukanken

08/12/2022, 7:57 AM
Honestly, too many parentheses can reduce readability too if the expression is so complex that you would need to add parenthesis around operators like
<=
then it's time to split it
val isDescending: Boolean = (h1 >= h2) && (h2 >= h3)
val isAscending: Boolean = (h1 <= h2) && (h2 <= h3)
val arranged: Boolean = isDescending || isAscending
Unnecessary nested parenthesis just obscure which ones are the pairs. Yes, IDE helps with that, or stuff like Rainbow brackets plugin, but it still denies you the just knowing start/end pairs on first glance
v

Vampire

08/12/2022, 9:41 AM
Well, that's highly subjective of course. Just saying how I do it and how the IDE also thinks it makes sense. 🙂 Of course anyone can do it like he wants or split things up or whatever.
View count: 4