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

    Pablo

    10/21/2020, 9:52 AM
    Is there any idiomatic way to avoid a huge when? Like when(string){ "blabla" -> {generateA} "bleble" -> {generateB} "blibli" -> {generateC} "bloblo" -> {generateE} "blublu" -> {generateD} .... } Is there any pattern that could help me out with this? For instance Command or Factory? This when is going to grow when I add more items, note each item have different behavior The example would be from my ViewModel I send this "type" to my useCase and my useCase decide what to do, because create N UseCase perhaps is a mess...
    n
    j
    r
    • 4
    • 10
  • p

    Peter Ertl

    10/21/2020, 10:16 AM
    general question: do I have to always write a coroutine variant of functions accepting lambdas? for example: fun doit(callback: () -> Unit) = … suspend fun doitAsync(suspend callback: () -> Unit) = … or can I somehow declare a function that accepts both suspending and non-suspending? I can imagine that ‘suspend’ adds overhead in the non-suspending case due a compiler generated state machine for supporting async. or: is it a reasonable approach to use runBlocking inside a non-suspending lambda or are there drawbacks?
    e
    • 2
    • 22
  • d

    Dávid

    10/21/2020, 10:22 AM
    Hey all, as far as I know we do not have any way of asserting that a generic class is a data class right? Is there a plan to introduce something like this? I think this is somthing that would be really useful. In my case I have an interface, and I want to define an extension method for the classes that implement that interface, and only for the ones that are data classes. In my head this could be totally written down like this:
    fun <data T: MyInterface> T.doSomethig() = copy(...)
    And I could get access to beautiful concepts like copy which comes with the
    data
    modifier on a class. Until this is functionality is implemented, do you know of a good way to do assert that the copy method exists in this scope?
    ➕ 1
    k
    e
    • 3
    • 19
  • p

    Peter Ertl

    10/21/2020, 10:44 AM
    is this the most elegant / proper way to use e.g. repeat() with a suspending function?
    suspend fun bla(): Unit = TODO()
    
    repeat(10) {
      runBlocking {
        bla()
      }
    }
    
    or do I need a suspendable version of repeat ("repeatAsync") ?
    m
    e
    • 3
    • 23
  • d

    Daniel

    10/21/2020, 1:35 PM
    In a hot loop more than 50% of my time is spent in a call to
    launch
    . How can I launch coroutines from a non-suspend function in a fire-and-forget way faster?
    m
    b
    r
    • 4
    • 51
  • n

    Nick

    10/21/2020, 2:10 PM
    The scoping functions (
    let
    ,
    apply
    ,
    also
    etc.) use
    contract
    which is marked as
    @Experimental
    . @Vsevolod Tolstopyatov [JB] suggested to not use shared flow in this

    video▾

    from the past event as
    SharedFlow
    was still experimental. He specifically pointed out to wait for a stable version if you work for a bank. Well, I currently work for a bank and I am told not to use anything marked as
    @Experimental
    . Since everything in
    standard.kt
    uses
    contract
    , does this mean these functions aren’t stable either?
    j
    e
    +2
    • 5
    • 10
  • d

    Daniel

    10/21/2020, 5:50 PM
    How can I detach from a sharedflow
    z
    e
    • 3
    • 11
  • l

    Lazar Ristic91

    10/21/2020, 8:48 PM
    I'm not sure is this is a right channel for this but, did anyone tried from
    Mindorks
    -
    Android Online Course for Professionals
    ? Or maybe has other Courses to recommend?
    n
    • 2
    • 1
  • n

    Nikhil

    10/22/2020, 7:41 AM
    Is there anyone from India who successfully registered on the Medium partner program?
    k
    • 2
    • 1
  • t

    taer

    10/22/2020, 4:02 PM
    Looking to make a delegate that returns the class name. Something like this:
    private val logger by OurLogger()
    I have a delegate working perfectly for class properties.
    class OurLogger {
        operator fun provideDelegate(thisRef: Any, prop: KProperty<*>) = LoggingDelegate(thisRef.javaClass.name)
    }
    class LoggingDelegate(klassName: String) : ReadOnlyProperty<Any?, Logger> {
        private val capturedLogger = LogManager.getLogger(klassName)
        override fun getValue(thisRef: Any?, property: KProperty<*>): Logger = capturedLogger
    }
    I can't get it to work though for top level properties. It seems to be looking for a
    provideDelegate(thisRef: Nothing?, prop: KProperty<*>
    which makes sense because it doesn't have a this. In my case, using the generated class that houses the static variable(aka, the fileNameKT) would be fine, but I can't figure out how to get the
    provideDelegate(thisRef: Any, prop: KProperty<*>)
    vs
    provideDelegate(thisRef: Nothing?, prop: KProperty<*>)
    to work. The second I make the thisRef Nothing, I can't do anything w/ it. I looked at the implementation of
    Lazy
    it seems to get away with it on the top level via an extension function
    kotlin.Lazy<T>.getValue(thisRef: kotlin.Any?, property: kotlin.reflect.KProperty<*>)
    Any advice on the top-level stuff?
    • 1
    • 3
  • u

    user

    10/22/2020, 4:11 PM
    message has been deleted
    🎉 7
    t
    • 1
    • 1
  • b

    Brian Dilley

    10/22/2020, 11:27 PM
    I have a C library that I’d like to use and am wondering if I can get around having to write jni bindings
    g
    d
    • 3
    • 4
  • b

    bodiam

    10/23/2020, 1:03 AM
    Hi all, I have the following code, and I was wondering how to unwrap my collection of optionals into the actual type. Is there a better way to do this in Kotlin?
    data class Alert(val message: String)
    val alerts : List<Optional<Alert>> = getAlerts()
    
    // filter 
    val messages = alerts
        .filter { it.isPresent }
        .map {it.get().message }
    n
    f
    t
    • 4
    • 104
  • m

    mattinger

    10/23/2020, 1:18 PM
    Anyone have a suggestion for how to do things like .map and .filter on a StateFlow without converting it to regular Flow object? Or does that just not make much logical sense? I can see how composition like that can throw a wrench into the current value management, but it seems like it’s kind of a miss.
    m
    • 2
    • 4
  • b

    Ben Madore

    10/23/2020, 1:40 PM
    any thoughts on this pattern to attempt to log the specific reason a chained boolean expression failed without having to have separate branches. (example is a bit contrived, just curious about thoughts on the pattern, or if there’s a better approach)
    fun Boolean.err(errorMessage: String): Boolean {
        if (!this) {
            <http://logger.info|logger.info> { errorMessage }
        }
        return this
    }
    ...
    if ((queryParams.size != 2).err("Expect exactly two query params but got ${queryParams.size}")
        || (queryParams["o"] == null).err("Query param o must be populated")
        || (queryParams["p"] == null).err("Query param p must be populated")
    ) {
        return badRequest().buildAndAwait()
    }
    n
    v
    • 3
    • 14
  • h

    Hamza

    10/23/2020, 2:03 PM
    wanted to share a usher parody/cover my friend wrote 😂
    Kotlin
    Aw man
    
    We at compile time
    IntelliJ on fullscreen from side to side
    Side-side to side
    This task, an easy one
    Compiling to bytecode tonight, night, night
    bytecode tonight
    
    Heads up
    You see a method with more than one expression
    Total shock fills your body
    Oh, no, it's you again
    I can never forget those line lines lines
    Lines-lines-lines
    
    'Cause, baby, tonight
    We're gonna be writing Kotlin again
    'Cause, baby, tonight
    You grab your map, filter, and run again (run again-gain)
    And run, run until it's done, done
    Until the sun comes up in the morn'
    'Cause, baby, tonight
    We're gonna be writing Kotlin again (Kotlin again-gain)
    😆 4
    a
    • 2
    • 2
  • h

    hnOsmium0x0

    10/23/2020, 4:09 PM
    Hi, I've met somebody who's having trouble getting an invite link to this server. According to him/her, nobody emailed him after a day (registered here https://surveys.jetbrains.com/s3/kotlin-slack-sign-up). Can anybody help with this? Also that page says I can invite people, but I don't find an option in the top-left dropdown?
    n
    • 2
    • 1
  • b

    Brian Dilley

    10/23/2020, 6:21 PM
    I’m writing a Kotlin Native app. programs will be run on many different architectures including mac/darwin x86_64, to linux x86_64, and even raspberry pi armv6/7. Are there any good libraries out there for file access yet? Basically I’m looking for something that takes the place of the java based stuff that we have in regular kotlin.
    m
    • 2
    • 13
  • k

    Ka Wing Chin

    10/23/2020, 7:10 PM
    Hello, I have a question about
    Dispatchers
    . I created an endless loop to create threads and see how the program will behave.
    class MainActivity : AppCompatActivity() {
    
        private val dispatcher: CoroutineContext = <http://Dispatchers.IO|Dispatchers.IO>
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val cores = Runtime.getRuntime().availableProcessors()
            println("Cores: $cores")
            println("===============================")
    
            endlessLoop()
        }
    
        fun endlessLoop() = runBlocking {
            withContext(dispatcher) {
                println(Thread.currentThread().name)
                while(true) {
                    launch {
                        println(Thread.currentThread().name)
                        while(true) {
                            // endless loop
                        }
                    }
                }
            }
        }
    }
    I got a phone with 4 cores and each core can handle 4 threads. If I would run this
    Dispatchers.Default
    . Then output will be:
    DefaultDispatcher-worker-1
    DefaultDispatcher-worker-2
    DefaultDispatcher-worker-3
    DefaultDispatcher-worker-4
    I get this, because all cores got occupied and working at 100% to get it done and no more tasks are allowed to be added. However if I run it with
    <http://Dispatchers.IO|Dispatchers.IO>
    which has 64 threads in the pool, it will run all 64 threads. I though it was 4 cores * 4 threads = 16 threads max. Can someone explain me why the program doesn't stop at
    DefaultDispatcher-worker-16?
    ✅ 1
    a
    • 2
    • 3
  • z

    zero_coding

    10/23/2020, 7:57 PM
    Would be nice, if someone could help:
    n
    • 2
    • 1
  • l

    liminal

    10/23/2020, 8:32 PM
    what would you say is a good example usage of
    .let {}
    on a non-nullable instance?
    n
    s
    • 3
    • 4
  • m

    Maxim Jaffe

    10/23/2020, 8:45 PM
    Hello, new to Kotlin. Does anyone know of a general purpose programming language (possibly dynamicall/gradually typed) implemented using Kotlin? Or an interesting external DSLs from a design/implementation point of view?
    p
    • 2
    • 1
  • p

    Pacane

    10/23/2020, 9:07 PM
    otherwise I guess I'll have to convert my flow to RxJava..?
    a
    • 2
    • 2
  • v

    v79

    10/24/2020, 11:32 AM
    My "hello world" fat jar is 1.6Mb... Is there any way of shrinking this down? I'm hoping to build an app for a Raspberry Pi, and will choose between Kotlin, C (or even assembly!) for programming it.
    a
    b
    +3
    • 6
    • 10
  • s

    stephanmg

    10/24/2020, 11:36 AM
    how about C with dietlibc? can you show your hello world in kotlin? 🙂
    v
    • 2
    • 10
  • g

    Gabriel

    10/24/2020, 2:32 PM
    How comes I can't create an extension function on Map with multiple signatures? https://pl.kotl.in/i5aSCMMgj but also I can't use Any, Any, so I'm not sure what's the best way to do it?
    a
    • 2
    • 4
  • d

    df

    10/24/2020, 2:48 PM
    Hey there. I'm building an app with kotlin and jpa. When starting the application I get the following error / warning
    org.hibernate.HibernateException: Getter methods of lazy classes cannot be final: SomeEntity#getFoo
    . The error is gone when I mark the property explicitly as open but from what I understood is that this should happen automatically with the jpa compiler plugin?
    j
    • 2
    • 4
  • w

    william

    10/25/2020, 2:30 PM
    when using kotlinx immutable classes, is it best to use the
    List
    type for return values or
    ImmutableList
    ? i don't want the downstream consumers to modify it (which either would provide). It kind of seems like an implementatino details that i am using
    ImmutableList
    n
    • 2
    • 5
  • t

    Tobi

    10/25/2020, 6:47 PM
    In this multi-modules Android project I am enabling explicit API mode in this commit. The compiler forces me to change a few classes and methods (adding
    public
    ), all in one module. ❓ Why are all other modules not affected although they do not declare
    public
    modifiers for their classes and methods?
    • 1
    • 1
  • a

    ahmad abas

    10/26/2020, 4:41 AM
    Hi, I am a web developer. I have a project that requires to also build on mobile apps to gain more potential customers. Usually should I build for android or iOS first? Thoughts?
    t
    • 2
    • 1
Powered by Linen
Title
a

ahmad abas

10/26/2020, 4:41 AM
Hi, I am a web developer. I have a project that requires to also build on mobile apps to gain more potential customers. Usually should I build for android or iOS first? Thoughts?
t

tipsy

10/26/2020, 9:01 AM
this isn't related to kotlin in any way, this is a business decision you have to make based on your target demographic and the skillset of your team
☝️ 2
👍 2
View count: 2