https://kotlinlang.org logo
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
  • r

    robstoll

    01/08/2021, 2:33 PM
    Nice to see that Kotlin gets a proper Path API (currently experimental). I guess I can soon reduce niok (https://github.com/robstoll/niok) to a few extra extension functions 👍
    v
    n
    m
    • 4
    • 18
  • j

    janvladimirmostert

    01/08/2021, 3:53 PM
    Out of curiosity, is this output always guaranteed across Kotlin JVM, Android, JS, Native, etc? I'm assuming Kotlin breaks up those ++i and i++ into separate lines?
    var i = 0
    val map = mutableMapOf<String, Int>()
    (1..10).forEach {
       map["${++i}"] = ++i + i++
    }
    println(map)
    {1=4, 4=10, 7=16, 10=22, 13=28, 16=34, 19=40, 22=46, 25=52, 28=58} To ask it differently, is the IR being generated always such that map[...] evaluates first, then the ++i and then the i++ ?
    v
    n
    a
    • 4
    • 13
  • c

    christophsturm

    01/08/2021, 4:27 PM
    is there a kotlin library that escapes strings to be safe as xml attributes? I could use https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html but I would really like to avoid adding a dependency
    j
    b
    r
    • 4
    • 5
  • d

    dm6801

    01/09/2021, 8:27 AM
    Hello kotliners,
    fun main() {
        fun fun1(name: String) = println("Hello $name")
        val fun2 = { name: String -> println("Hello $name") }
        function(::fun1)
        function(fun2)
    }
    
    fun function(callback: (name: String) -> Any) {
        //some complicated calculation
        callback("username")
    }
    Which one would you use, and why?
    e
    v
    s
    • 4
    • 16
  • c

    Chilli

    01/09/2021, 12:44 PM
    Is there any public API Kotlin annotation (like
    [PublicAPI]
    attribute in JetBrains Annotations .NET library) that would mark a class/method/… as public API and therefore stop showing warnings
    Property could be private
    ?
    y
    m
    • 3
    • 7
  • c

    CLOVIS

    01/09/2021, 8:43 PM
    Let's say I wanted to create a 3D game which requires access to some low level functions (for example Vulkan APIs), and I didn't like the C or C++ syntax. What are the options for Kotlin? • Fully using the JVM, with LibGDX or jMonkeyEngine. However, it's impossible to access low level functions directly. • Using an hybrid of JVM and C via JNI. However many benchmarks seem to suggest the speed aspects are not that great, because anything other than primitives must be copied back and forth to ensure thread safety. One solution could be to avoid arrays as much as possible and try to have as few native calls as possible, but it might not be doable as many calls might be required per frame • Fully native, however to my understanding Kotlin/Native is built for low RAM usage and not for fast speeds. The inability to ‘unfreeze' objects might be very good for IoT, but it doesn't sound that good for 3d game—please enlighten me if you have more insights for this. None of these solutions sound good, is there any I missed, or is it just not possible (at least currently)? I'm aware video games is probably not very high in Kotlin's roadmap, but I'm curious as to how it could compare to C# and other high level languages that are used.
    e
    d
    +3
    • 6
    • 14
  • a

    andries.fc

    01/10/2021, 4:24 AM
    Does anyone know how construct KClass from Java? The reason I'm asking because I'm integrating a library into my app which uses a factory interface defined in Java, and I need to know from Java if class is in actual fact an Object instance?
    t
    • 2
    • 3
  • p

    paul Olukayode

    01/10/2021, 5:42 PM
    Is there any kotlin library that sopport xmpp
    v
    g
    • 3
    • 9
  • s

    Safa Orhan

    01/11/2021, 10:41 AM
    Hello folks! I am an Android Developer / Trainer from Turkey. Currently I am working for my business on Kotlin / Android Dev training. Creating educational resources, shooting YouTube videos, writing blog posts and such. Nice to meet you all, let me know if we can collaborate on any thing (conference, workshop, live stream, etc.)
    :kotlin-intensifies: 6
    • 1
    • 1
  • a

    Animesh Sahu

    01/12/2021, 4:10 AM
    🤔 https://stackoverflow.com/q/65677685/11377112
    • 1
    • 1
  • s

    scaventz

    01/12/2021, 9:57 AM
    Kotlinc
    supports the option
    -script
    , but I can’t find detailed information about it. Where can I find the relevant documentation about kotlin script?
    b
    g
    +2
    • 5
    • 8
  • j

    james

    01/12/2021, 2:44 PM
    Anyone know of any good resources for "why kotlin"?
    s
    a
    +4
    • 7
    • 14
  • m

    mikehearn

    01/12/2021, 4:28 PM
    It hasn’t received any commits for three months.
    :thread-please: 1
    v
    o
    +2
    • 5
    • 9
  • c

    crummy

    01/12/2021, 6:27 PM
    I'd like to write Kotlin code server-side, with APIs that implement an interface, and auto-generate JS (or TS, even better) clients for my interfaces. The idea is, if I needed data from the backend, I'd add a method to the interface, regenerate the clients, and now it's available for use. I'm not 100% sure how to go about this though. One option I thought would be to use OpenAPI and maybe get Gradle to autogenerate clients. Is there a better way to do this?
    h
    p
    +2
    • 5
    • 12
  • m

    muliyul

    01/13/2021, 12:22 AM
    Hey everyone this is not really related to Kotlin but I need help. I have an HTML I'd like to replace a portion of it (a json object) with my json. the markup looks like this
    [html...] SwaggerUIBundle({ ... }) // the object I'm trying to replace is the parameter to this factory
    [...html]
    The object may have indentation, new lines etc. I came up with this:
    html.replace("""\s*\{(\s*.*)*}\s*?""".toRegex(), myJsonFormattedString)
    But since the expression resides between js brackets the regex is matching all the way to the closing bracket for example:
    { ... }) [...javascript] }
    I tried to use the non-greedy modifier but it didn't seem to work. Your help is appreciated!
    m
    • 2
    • 1
  • r

    rajesh

    01/13/2021, 9:03 AM
    have two tables as following Post table and Comment table I need to create another table called Activity table which will store aggregate values of likes performed on post or comment. I want to use activity id column which must be EITHER post id or comment id. How do i do enforce this condition in database? (preferably hibernate)
    d
    v
    • 3
    • 10
  • a

    Arief Hidayat

    01/14/2021, 7:15 AM
    #Ask any one know how to make this object inside array programmatically
    k
    s
    m
    • 4
    • 4
  • a

    Arthur Artikov

    01/14/2021, 11:16 AM
    Hi. What is the best way to get a delegate from a delegated property? I need it to wrap MutableStateFlow to a property delegate for my mini MVVM-framework. getDelegate requires kotlin.reflect package that is not optimal for Android development. I came up with this solution https://gist.github.com/aartikov/b64f462f50b5e5452c3df707db090a5f It uses a global (ThreadLocal to be more precise) holder to place a delegate there from getValue method. Do you have ideas how to implement it better?
    d
    • 2
    • 6
  • a

    Andrew Adams

    01/15/2021, 12:01 AM
    Hey guys I was curious is there was a super class that all classes that have a companion object inherit, and thusly can be extended? To enable the use of extension methods such as:
    inline fun <reified T : Any> T.Companion.extensionMethod = ...
    z
    t
    • 3
    • 5
  • h

    holgerbrandl

    01/15/2021, 8:51 AM
    How can I express else branches of for loops in kotlin? Python supports this (imho obscure feature) (see https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops), but I want/need to port some python code to kotlin. In python the
    else
    after a for loop it is executed when the loop terminates through exhaustion of the iterable but not when the loop is terminated by a 
    break
     statement.
    Here is the yet non-functional example from the python docs ported to kotlin
    for(n in (2..10)){
        for(x in (2.. n)){
            if(n.rem(x)==0){
                println("$n equals $x * ${n/x} ")
                break
            }
        }
        //todo else{ ???
        // loop fell through without finding a factor
        println("$ is a prime number")
    }
    d
    a
    n
    • 4
    • 21
  • n

    natpryce

    01/15/2021, 1:18 PM
    When I use sealed classes, I end up writing lots of functions like:
    fun doSomethingWith(arg : SealedBaseClass, otherArg: Int) = when(arg) {
        is SubclassA -> doSomethingWith(arg, otherArg)
        is SubclassB -> doSomethingWith(arg, otherArg)
     }
    
    fun doSomethingWith(arg : SubclassA, otherArg: Int) = ... 
    fun doSomethingWith(arg : SubclassB, otherArg: Int) = ...
    What do people think of the idea of a sealed function, where the compiler generates the when boilerplate for you? E.g.
    sealed fun doSomethingWith(arg : SealedBaseClass, otherArg: Int)
    
    fun doSomethingWith(arg : SubclassA, otherArg: Int) = ... 
    fun doSomethingWith(arg : SubclassB, otherArg: Int) = ...
    I’m imagining the same rules would apply as for sealed classes: all implementations of the sealed function have to be in the same source file. And the compiler would check them for exhaustiveness.
    ➖ 2
    ❤️ 8
    s
    l
    +2
    • 5
    • 23
  • n

    Nir

    01/15/2021, 4:01 PM
    If you want to write a DSL where the user can call some function to "break out" early from their own function, does this have to be implemented using exceptions internally? Is this considered bad? Here's a toy attempt at emulating python's else clause on for loops:
    class BreakException : Exception("")
    
    class Breaker {
        fun breakOut() { throw BreakException(); }
    }
    
    class ForEachElser(val runElse: Boolean)
    
    fun <T> Iterable<T>.forEachElse(func: Breaker.(t: T) -> Unit): ForEachElser {
        val b = Breaker()
        return try {
            forEach{ b.func(it) }
            ForEachElser(true)
        }
        catch (b: BreakException) {
            ForEachElser(false)
        }
    }
    
    infix fun ForEachElser.elser(func: () -> Unit) { if(runElse) func() }
    👀 1
    c
    h
    +2
    • 5
    • 20
  • n

    Nir

    01/15/2021, 4:32 PM
    A separate DSL type question. One thing I've frequently encountered with DSL's that's a bit annoying is that infix functions generally cannot start a line. So if you are writing something that emulates an
    else
    or other control flow, as above, then I'd like to be able to write:
    something {
        ...
    }
    my_else {
        ...
    }
    but this will never compile, you need to put the
    my_else
    after the brace. Does it seem reasonable at all that the compiler could consider allowing this to compile, specifically when you have an infix function starting a line like that
    c
    • 2
    • 3
  • d

    dMusicb

    01/15/2021, 9:29 PM
    Is there a way to monitor/assert there are no coroutines in a pending (maybe wrong word) state? i.e. I have a piece of code that dispatches some work in a coroutine on Dispatchers.IO and I'm having some trouble with it bleeding over between integration tests so I want to have a check that confirms all coroutines have completed
    b
    a
    • 3
    • 2
  • i

    Ifvwm

    01/16/2021, 6:32 AM
    what String! mean? File(uri).length, it shows me none of the following functions can be called with arguments supplied public constructor File(uri: URI!)
    📖 1
    r
    • 2
    • 1
  • o

    Oliver Eisenbarth

    01/16/2021, 11:48 AM
    Hi, I wanted to test improvements to inline classes in KT-1.4.30-M1. I thought it was possible to have inline classes with internal / private constructors? Is this not possible? If you want to have a look, here's some code.
    i
    y
    • 3
    • 5
  • r

    Remy Benza

    01/16/2021, 12:19 PM
    Is there a way of serializing a
    MutableList<Pair<Pair<String, Boolean>, Triple<String, String, Boolean>>>
    type with the kotlinx serialization lib without writing a custom type converter?
    n
    j
    +2
    • 5
    • 18
  • s

    serebit

    01/16/2021, 6:15 PM
    I created an issue for inserting a value for a constant at compile time, the one feature I miss from Go. Link: https://youtrack.jetbrains.com/issue/KT-44386
    d
    • 2
    • 7
  • r

    robstoll

    01/16/2021, 9:08 PM
    Is there any plan to support de-structuring nested classes which implement
    component...
    in the same line? So that something like the following would work:
    val (a, (b, c)) = 1 to (2 to 3)
    ➕ 6
    🔥 5
    g
    h
    • 3
    • 2
  • z

    Zimri Leisher

    01/17/2021, 2:37 AM
    on a very simple program, gradle is getting stuck on every step and working very slowly: compiling kotlin, building, even running the main function. and when i call readLine(), the delay between me pressing enter andthe line being read is like 30 seconds
    a
    • 2
    • 7
Powered by Linen
Title
z

Zimri Leisher

01/17/2021, 2:37 AM
on a very simple program, gradle is getting stuck on every step and working very slowly: compiling kotlin, building, even running the main function. and when i call readLine(), the delay between me pressing enter andthe line being read is like 30 seconds
the computer is otherwise fine, nothing else is occupying cpu
and memory is less than half used
the gradle classes task takes a minute even with no change to the code at all and 1 total class
i restarted computer, and changed the shared heap size to like 4 gbs
a

Alexey Belkov [JB]

01/18/2021, 11:33 AM
Do you use both Gradle and IDE Kotlin plugin 1.4.21? Do you compile from CLI or in IDEA?
z

Zimri Leisher

01/20/2021, 5:58 AM
I initially was compiling with gradle and ide kotlin plugin
but i tried with IDEA and it works fast
View count: 3