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

    Brian Nicholson

    04/28/2021, 8:05 PM
    Hello, any Dokka experts here? I'm dealing with a huge monorepo that uses the Buck build system, and I'm trying to generate KDoc for just a tiny sliver of that codebase. I created a
    build.gradle.kts
    specifically for Dokka with a
    sourceSet
    containing just the subdirectory I'm interested in, and it generates documentation, but the problem is that any dependency outside of my
    sourceSet
    is shown as
    <ERROR CLASS>
    . Obviously, Dokka can't generate docs for these classes since it can't resolve them, but is there there any way to get these class names to appear as text rather than an error? Ideally, I'd be able to link these unresolved classes to a URL containing their source code, but even just getting the raw text name would be a huge improvement.
    z
    • 2
    • 1
  • k

    Karlo Lozovina

    04/28/2021, 8:07 PM
    Will overriding of
    equals()
    for inline classes be available in the future?
    n
    r
    • 3
    • 29
  • d

    David Smith

    04/29/2021, 9:51 AM
    I’m just learning about gradle “platforms” and was wondering if anyone aware of a community maintained gradle platform or similar that basically has every dependency you could ever want? Coming from the Haskell world we have https://www.stackage.org/ which basically gets rid of a huge amount of dependency hell.
    b
    j
    +2
    • 5
    • 25
  • r

    Rob Elliot

    04/29/2021, 11:41 AM
    Is there an annotation like
    @Deprecated
    but meaning specifically that a method call is pointless, because it returns
    this
    and has the same return type as the object it is called on? For instance,
    String.toString() = this
    would be a candidate for it.
    c
    b
    +2
    • 5
    • 8
  • u

    user

    04/29/2021, 12:30 PM
    message has been deleted
    👏🏻 1
    :kotlin-intensifies: 16
    👏 4
    ❤️ 2
    b
    • 1
    • 1
  • e

    eygraber

    04/29/2021, 3:27 PM
    I know 1.5 isn't officially released yet, but I can get the artifact so I started migrating my project to it. However, anything added in 1.5 results in a unresolved reference. Is that expected until the full rollout of the release?
    d
    s
    • 3
    • 9
  • s

    Stefan Beyer

    04/29/2021, 3:56 PM
    uuuh... can someone explain to me why
    (19.999996 * 100.0).roundToInt().toDouble() / 100.0
    is sometimes 20.0 and sometimes 0.0? this is really unexpected ^^
    n
    • 2
    • 7
  • g

    Gerard Bosch

    04/29/2021, 5:25 PM
    Hi there, is it possible to do this in Kotlin somehow? (it is just an example) I get error at call-site:
    Unresolved reference: of
    sealed class Sealed {
        
        // Is it possible to define a factory method or smart constructor here?
        fun of(n: Int): Sealed = if (n > 0) Foo("test") else Bar(42)
        
        data class Foo(val str: String) : Sealed()
        data class Bar(val num: Number) : Sealed()
    }
    and why is the above not possible? thank you!
    n
    h
    +2
    • 5
    • 23
  • p

    Philipp Mayer

    04/29/2021, 5:30 PM
    General question for everyone: Is there a specific codebase that you love to go through to learn new things? For example from time to time I just go through the http4k-connect to see and learn how to integrate other systems in a kotlin idiomatic way. I'd love to learn about your recommendations!
    👍 3
    🙂 2
    m
    • 2
    • 2
  • n

    nkiesel

    04/29/2021, 8:04 PM
    Is there a good way to test a string against a series of regex without matching twice? Right now I have
    for (line in lines) {
       if (Regex("#(.) A (.+)").matches(line)) {
           val m = Regex("#(.) A (.+)").matchEntire(line)
            ...
       } else if (Regex("#(.) B (.+)").matches(line)) {
           val m = Regex("#(.) B (.+)").matchEntire(line)
           ...
       }
    }
    (real code of course has regexes defined only once etc.). I now changed it to
    for (line in lines) {
       val m1 = Regex("#(.) A (.+)").matchEntire(line)
       if (m1 != null) {
          ...
          continue
       }
       val m2 = Regex("#(.) B (.+)").matchEntire(line)
       if (m2 != null) {
          ...
          continue
       }
    }
    but that does not look too nice (esp. the need for repeated
    continue
    )
    n
    n
    e
    • 4
    • 13
  • k

    Karlo Lozovina

    04/29/2021, 8:30 PM
    Given that
    lateinit
    can't go on primary constructor parameters, is there a less manual way of doing something like this (lateinited class fields that can be set through the constructor)?:
    class Foo(x: String? = null) {
        lateinit var x: String
        
        init {
            if (x != null) this.x = x
        }
        
        fun show() = println("Foo: $x")
    }
    s
    j
    +2
    • 5
    • 31
  • c

    coroutinedispatcher

    04/29/2021, 9:31 PM
    Hello Kotliners. Is there a way to give an actual name to callback functions so that I don’t have to implement a bunch of
    invoke()
    methods? For example:
    class Whatever(val callbackNumber1: (SomeParameter) -> Unit, val callbackNumber2: () -> Unit)
    So now when call that instance in another object, I would have something like this:
    class AnotherObject : (SomeParameter) -> Unit , () -> Unit {
       private val whatever = Whatever(this, this)
    
       override fun invoke(){
    
       }
    
       override fun invoke(someParameter: SomeParameter){
        
       }
    }
    Or should I just stick to plain interfaces in this case?
    n
    z
    +2
    • 5
    • 12
  • m

    Michael Böiers

    04/30/2021, 12:46 PM
    I’m wondering why the if statement doesn’t expect a nullable Boolean type. What would be the disadvantage of allowing it? Consider this:
    if (foo?.isNotEmpty() ?: false) { … }
    That works, but it’s not really concise. Wouldn’t it be better (and safe) if we could just write
    if (foo?.isNotEmpty()) { … }
    👍 1
    🇳🇴 3
    s
    c
    +5
    • 8
    • 78
  • c

    Cicero

    04/30/2021, 3:52 PM
    Hey people, where can I discuss testing with Kotlin?
    e
    t
    b
    • 4
    • 17
  • t

    Tom Wayne

    04/30/2021, 4:58 PM
    Hello guys, I am currently trying to connect our Kotlin Multiplatform Project to websockets. I would like to use ktor-websockets library to receive some updates from our backend but onfortunately when I run this code, nothing happens:
    client.webSocket(
        port = 80,
        method = HttpMethod.Get,
        host = "<https://uat-betws.sts.pl>",
        path = "/ticket?token=eyJzdWIiOiI0ZmY5Y2E1Mi02ZmEwLTRiYWYtODlhYS0wODM1NGE2MTU0YjYiLCJpYXQiOjE2MTk4MDAwNzgsImV4cCI6MTYxOTgwMzY3OH0.oIaXH-nFDpMklp4FSJWMtsM7ECSIfuNF99tTQxiEALM"
    )
    {
        for (message in incoming) {
            message as? Frame.Text ?: continue
            val receivedText = message.readText()
            println(receivedText)
        }
        // Consume all incoming websockets on this url
        this.incoming.consumeAsFlow().collect {
            logger.d("Received ticket status websocket of type ${it.frameType.name}")
            if (it is Frame.Text) {
                Json.decodeFromString<TicketStatusResponse>(it.readText())
            }
        }
    }
    Does somebody have any experience with ktor-websockets library? There is almost no documentation so maybe I am doing something wrong. Thank you
    b
    • 2
    • 1
  • s

    Slackbot

    04/30/2021, 8:04 PM
    This message was deleted.
    :not-kotlin: 2
    n
    b
    • 3
    • 3
  • p

    Patrick Ramsey

    05/01/2021, 1:06 AM
    Also general kotlin question from a relative newbie: several months in, I still feel like I don’t fully grok kotlin’s position on the function of exceptions. There is this blog post: https://elizarov.medium.com/kotlin-and-exceptions-8062f589d07 that seems to be basically saying that you should only use exceptions where you’d use assert() (ie, to signal logic errors), and most of the time you shouldn’t be catching exceptions --- ie, try/catch blocks are a code smell. There are some obvious … exceptions to that rule (such as, catching exceptions thrown by java code), but --- fair enough, error states should be signaled through special return values, either null or a special instance of a sealed class. … but then I go out into the world, and I don’t see that pattern being followed. For instance, ktor (which a number of blog posts have nudged me towards as a good sane default http client for kotlin) by default uses exceptions to signal http error codes. IE --- rather than exceptions indicating a bug, ktor throws exceptions to indicate that a potentially expected error has occurred. I’m fine with this pattern, too! But it makes it hard to see what I should adopt in my own code.
    👀 2
    r
    h
    +2
    • 5
    • 43
  • l

    LastExceed

    05/01/2021, 11:26 AM
    class Thing(parameter: Int) : List<Int> by property { //unresolved reference: property
    	val property = listOf(parameter)
    }
    why isn't this allowed?
    b
    e
    • 3
    • 4
  • t

    Thorkild

    05/01/2021, 6:39 PM
    Is there anything particular that drives up the kotlin compiler memory usage that one should look out for? I am generating code using Kotlinpoet and I am struggling with very high memory usage during compilation (I had the similar problem in an earlier project with 1.3.x, but back then it was enough to just give it more memory -- now that doesn't solve it due to a higher number of classes). The code generated is not deep (so no big nested if-s or anything, but 3 methods, a number of static variabled defined in the companion object. I guess the most risky might be a data class that has about 20000 different uses. It is currently just over 600 such classes, and they are in the same package -- would splitting up the packages help?
    d
    • 2
    • 5
  • b

    Brian Dilley

    05/01/2021, 8:12 PM
    i know this is the wrong slack for this, but whatever happened to java modules? i feel like nobody uses them or cares about them.
    👎 1
    :not-kotlin: 6
    m
    c
    +3
    • 6
    • 11
  • m

    Matěj Bystřický

    05/01/2021, 11:25 PM
    Hi everyone! Don't know if this is the right place to ask, but do any of you have any experience with writing iOS app in Kotlin, particularly with Jetpack Compose?
    r
    c
    • 3
    • 8
  • l

    LastExceed

    05/02/2021, 3:12 PM
    why does
    const
    need to be specified explicitly? can't the compiler check automatically if the keyword is applicable ? or is there a scenario where you wouldn't want its optimizations ?
    a
    c
    m
    • 4
    • 4
  • m

    Mark

    05/03/2021, 2:09 AM
    Where is the appropriate place to report code completion (AS) issues?
    fun (String.() -> Unit).test() {
        "anything to demonstrate the point".apply {
            // no code completion for "this" -> "this@test"
            "something".this()
        }
    }
    e
    y
    j
    • 4
    • 8
  • l

    LastExceed

    05/03/2021, 2:45 PM
    is there a way to make a
    Map
    that's guaranteed to be exhaustive, so the return type of
    get()
    isn't nullable? (similar to how
    when
    can skip
    else
    when it's exhaustive)
    r
    c
    +4
    • 7
    • 12
  • a

    andreasmattsson

    05/03/2021, 4:02 PM
    Why does this work:
    data class TestContainer(
    	val body: Any?
    )
    
    operator fun TestContainer?.compareTo(b: TestContainer?): Int = this?.body.let { aBody ->
        b?.body.let { bBody ->
            when {
                aBody is Boolean && bBody is Boolean -> {
                    val aBoolean: Boolean = aBody
                    val bBoolean: Boolean = bBody
                    return aBoolean.compareTo(bBoolean)
                }
                else -> -1
            }
        }
    }
    
    fun main() {
    	println("Comparison: ${TestContainer(true) < TestContainer(false)}")
    }
    But the following yields ClassCastException at runtime on JVM?
    data class TestContainer(
    	val body: Any?
    )
    
    operator fun TestContainer?.compareTo(b: TestContainer?): Int = this?.body.let { aBody ->
        b?.body.let { bBody ->
            when {
                aBody is Boolean && bBody is Boolean -> aBody.compareTo(bBody)
                else -> -1
            }
        }
    }
    
    fun main() {
    	println("Comparison: ${TestContainer(true) < TestContainer(false)}")
    }
    Error is
    Exception in thread "main" java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Number
    I'd expect the two to be equivalent due to smart cast?
    t
    • 2
    • 4
  • n

    Nthily

    05/03/2021, 7:21 PM
    Has anyone had this problem? I can't find the
    MainClass
    in the jar I generated with
    Gradle
    package
    r
    e
    • 3
    • 49
  • a

    Andrew Gazelka

    05/03/2021, 10:46 PM
    ummm…. is this a bug?
    🤔 1
    a
    i
    • 3
    • 2
  • k

    Kirill Grouchnikov

    05/03/2021, 10:49 PM
    Is 1.5.0 still not officially released? Stuck on IDEA plugin updates?
    🙂 1
    n
    b
    • 3
    • 2
  • m

    Mark

    05/04/2021, 3:10 AM
    What is the simplest/best
    Regex
    that will never find/match any input string? Seems that each regex engine out there has a different best practice for making an ‘impossible’ regex.
    l
    e
    v
    • 4
    • 23
  • d

    df

    05/04/2021, 1:35 PM
    Hey. We are looking for a kotlin freelancer for a 3 months period (jun. to aug.) any recommendations? (is there a better suited channel for this random question?)
    d
    • 2
    • 2
Powered by Linen
Title
d

df

05/04/2021, 1:35 PM
Hey. We are looking for a kotlin freelancer for a 3 months period (jun. to aug.) any recommendations? (is there a better suited channel for this random question?)
d

dave08

05/04/2021, 1:35 PM
#hiring or look in #hire-me
d

df

05/04/2021, 1:36 PM
thanks
View count: 1