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
getting-started
  • д

    Дмитрий Цывцын

    02/03/2022, 2:30 AM
    Hello. If you are starting to learn algorithms, use my repository with the simplest and most famous algorithms on Kotlin!!!! Algorithms on Kotlin
    🙌 1
    🙌🏻 1
    a
    • 2
    • 6
  • x

    xii

    02/03/2022, 8:33 AM
    lets say you want to apply something to the result of a completable future in a coroutine, but only after the completable future finishes and you don't want to explicitly await it, how would you do it?
    j
    • 2
    • 9
  • j

    Jan

    02/03/2022, 3:21 PM
    what am I doing wrong? I also cant compile the code. The function itself has no error
    k
    m
    h
    • 4
    • 12
  • k

    Karlo Lozovina

    02/03/2022, 4:21 PM
    what's the idiomatic way to check if 3 or 4 or even more variables are all the same? something like a == b == c == d ... ?
    c
    d
    +2
    • 5
    • 5
  • s

    Skc

    02/04/2022, 3:42 AM
    Hey everyone 👋 I am trying to create a gson type adapter to process the object after it is de-serialized, following the pattern described here, https://github.com/google/gson/tree/master/extras/src/main/java/com/google/gson/interceptors However, not getting the right approach to convert that impl to Kotlin . Specifically, using generic type on an interface and apply the interface to an annotation class. Could someone provide any ideas or hint to get this approach right. This is what I have got so far, https://gist.github.com/sushant-droid/a3b673f513717b43550950cbcc1307cb
    e
    • 2
    • 3
  • a

    Advitiay Anand

    02/04/2022, 8:04 AM
    Is Kotlin for JS a good option for devs who have not worked with JS / web before? Or does it assume familiarity with JS and its ecosystem?
    r
    • 2
    • 2
  • k

    Kenneth

    02/04/2022, 9:59 AM
    Is there a recommended way in Kotlin to validate a BigDecimal to confirm with e.g.
    totalDigits(10) fractionDigits(3)
    ?
    m
    • 2
    • 2
  • m

    Mark

    02/04/2022, 10:30 AM
    Playing around with
    buildMap
    but please can someone explain why this gives a compilation error (unless I uncomment the null):
    fun main() {
        buildMap {
            if (true) {
                println("test")
                // null
            } else {
                put("foo", "bar")
            }
        }
    }
    https://pl.kotl.in/sohJmyPiJ
    g
    j
    v
    • 4
    • 13
  • a

    abbic

    02/04/2022, 11:48 AM
    hey, posting this here because i cant find a pure kotlin questions channel, what is the difference between, in a class, having
    Class {
        fun foo() { // normal method definition }
        val foo = { // same method implementation, but its a lambda }
    }
    t
    g
    +2
    • 5
    • 12
  • j

    Justin Xu

    02/04/2022, 6:16 PM
    Hi everyone, I'm getting started with KMM with cocoapods as outlined in the documentation on the website, but I keep running into this error:
    'pod install' command failed with an exception:
    Cannot run program "pod" (in directory "...../iosApp"): error=2, No such file or directory
    I installed cocoapods using ruby2.7.5, and I am on M1 mac, following the troubleshooting guide here(youtrack.jetbrains). My "pod install" command also works in the folder, I am just not sure why this error keeps showing up.
    s
    • 2
    • 1
  • n

    nkiesel

    02/04/2022, 8:39 PM
    just drawing a blank here: is the not a shortcut for
    if (predicate(x)) f(x) else null
    ?
    e
    d
    s
    • 4
    • 6
  • a

    Ansh Tyagi

    02/05/2022, 12:45 PM
    Not sure what the right channel would be to ask this, but is there a hack to get a map of the named params of a function to their value. For example:
    fun xyz(param1,param2,param3...)
    and get something like
    {"param1":param1, "param2": param2 … }
    its very laborious and redundant to do mapOf. Any workarounds?
    j
    j
    m
    • 4
    • 8
  • a

    Ayfri

    02/05/2022, 2:57 PM
    Hey, is it possible to make an abstract enum ? Or a type that is equal to Enum<T> with added methods ?
    j
    r
    m
    • 4
    • 16
  • j

    Jan

    02/06/2022, 5:54 PM
    I'm not sure when exactly I'd use a value class. Does it make sense for something like this: (see thread)?
    k
    n
    +2
    • 5
    • 6
  • j

    Josh Davis

    02/07/2022, 3:24 PM
    Hey everyone 👋🏻 I'm new to the community and would love some recommendations on resources to learn Kotlin. Any of your favorite books, courses, video series etc would be greatly appreciated!
    👋 4
    j
    s
    +2
    • 5
    • 5
  • r

    Ruckus

    02/07/2022, 6:54 PM
    The new Kotlin scripting tutorial (https://kotlinlang.org/docs/custom-script-deps-tutorial.html#project-structure) contains this little gem, and I cannot tell if it's a bug or a pun.
    :ladybug: 1
    🤣 3
    l
    • 2
    • 1
  • m

    Michael Langford

    02/07/2022, 7:38 PM
    fun JsonObject.get<reified T : Enum<T>>(key: T): JsonElement {
      return this.get(key.name)
    }
    Hi there, I'm trying to make a generic function that helps make my json parsing a little easier. I'm trying to make it so I can pass any enum, rather than having to make a specific copy of this method for each of the decoding enums I'm using. It seems I'm messing up the syntax for saying "key is a value of some enum type". This is the only way I'm using this (to get the name of the key item), so I don't actually care if it's reified if I don't need to do so to implement this function. Can anyone steer me towards how to write this correctly? Non generic version:
    fun JsonObject.get(key: EntryTypeAADeserializer.CodingKeys): JsonElement {
      return this.get(key.name)
    }
    ✅ 1
    s
    • 2
    • 3
  • t

    Tim Oltjenbruns

    02/08/2022, 1:55 AM
    Hello everyone. I’m having a hard time with an extension function on an out projected type.
    fun <Next, Root> KProperty0<Next>.set(value: Next) = Value<Next, Root>(this, value)
    Because KProperty0 is out projected, I don’t get any type checking for the value parameter. If the property is a String, I can put an Int in the value because they both inherit from Any. Is there anything I can do to make the type checking more rigid on this function? Looking for a more invariant type checking.
    p
    • 2
    • 12
  • c

    Chang Kenneth

    02/08/2022, 6:44 AM
    hello, everyone I have a question about coroutine, in the demo from document, they launch 100,000 child coroutine, each of them delay 5 seconds, I understand delay is suspend function, and I read source code, it will use handler(android) to deal with time(5 seconds) but the question I got is, cpu only proceed the task in thread, once the delay function suspend, how does it wait for complete, in handler, queue, or just switch between threads? and what if i actually make 100,000 api request, does it perform as well?
    //sampleStart
    fun main() = runBlocking {
        repeat(100_000) { // launch a lot of coroutines
            launch {
                delay(5000L)
                print(".")
            }
        }
    }
    c
    • 2
    • 3
  • a

    Ayfri

    02/08/2022, 3:50 PM
    Hi, I have a simple question, why inline function is only useful when there is a lambda as last argument ? Why couldn't use inline functions at other places ?
    r
    c
    +2
    • 5
    • 15
  • a

    Advitiay Anand

    02/08/2022, 8:33 PM
    Hi everyone, I've got a Kotlin project (not Android) that involves many variables with user-specific values (e.g. username, password, time-table) I would like this data to be moved out of the code, and into a modifiable file. The goal is to make it easy for non-coders to modify values and use the program. What are my best bets here? (JSON / YAML / etc). And what library should I be using? Here's a link to the project: https://github.com/adizcode/ProxyMate
    t
    p
    o
    • 4
    • 8
  • t

    tomas-mrkvička

    02/08/2022, 8:34 PM
    Hello everybody. I am fighting internally with Roman's article about exceptions: https://elizarov.medium.com/kotlin-and-exceptions-8062f589d07. I am not convinced about main parts of the article and would like to know how you guys handle them in real-world applications. Especially what type of exceptions you declare in KDoc. Whether you go deep within your function call stack and try to be as exhaustive as possible about exceptions. And on the caller side, whether you simply have
    try { } catch(e: Exception) { }
    just to be sure you don't miss anything even if the bottom API change?Thanks.
    m
    t
    +2
    • 5
    • 24
  • r

    Razine Ahmed Bensari

    02/08/2022, 8:43 PM
    Hello, I have a small question 🙂 Is there a reason why the
    suspend
    keyword is required for function executed inside coroutines ?
    k
    h
    • 3
    • 2
  • j

    Jan

    02/08/2022, 8:56 PM
    Is there an easy way to convert an Int to a ByteArray in Kotlin (Multiplatform so no JVM methods)
    t
    • 2
    • 2
  • b

    Bernard Ng

    02/09/2022, 3:41 AM
    Hello I'm new to kotlin, I'm still learning and I was wondering if there is any kotlin online course with a «valuable» certification I can get, any idea ? PS : Kotlin for web (server)* not Android
    g
    t
    • 3
    • 4
  • s

    smit01

    02/09/2022, 6:31 AM
    class A(val value:Int = 0) fun test(){ with(A(9)){ with(A(8)){ println(this.value) //output 8 println(this@with.value) //output 8 // My question is how to access A's object with value 9 } } }
    e
    j
    • 3
    • 5
  • l

    LastExceed

    02/09/2022, 12:53 PM
    why doesn't L13 work ?
    Untitled.kt
    s
    • 2
    • 7
  • b

    Bart Kleijngeld

    02/09/2022, 3:40 PM
    I'm getting a type error that I don't understand, and was hoping someone could help me with it.
    import java.io.File
    
    private fun Format(filename: String): Format? {
        // Never mind the implementation here.
    }
    
    fun readFiles(files: Sequence<File>): Map<Format, List<Reader>> =
        files
            .groupBy { getFormat(it.toString()) }
            .filterKeys { it != null }
            .mapValues { it.value.map { f -> f.reader() } }  // ERROR: Type mismatch: inferred type is Format? but Format was expected
    s
    j
    +3
    • 6
    • 17
  • p

    Priya

    02/09/2022, 8:36 PM
    Is there
    OrderedSet
    (not sorted) in Kotlin? Any alternatives?
    e
    p
    • 3
    • 10
  • m

    Michael Langford

    02/09/2022, 9:56 PM
    Is there a simple way to execute functions in parallel and wait until all are done? All the examples I find when googling appear to expect a blocking style function instead of already async functions. For instance, I have multiple api endpoints I need to hit, but I don't want to do the model/screen refresh until all 3 have returned. I've simplified the prototype of the functions here a bit for explanatory purposes. I definitely need to call some of these at other times, and don't really want to change their prototype.
    fun fetchActivities(userName:String,  completion:(List<ActivityEntry>)->Unit) {}
    
    fun fetchMoves(userName:String,  completion:(List<MoveEntry>)->Unit) {}
    
    fun fetchScores(userName:String,  completion:(List<ScoreEntry>)->Unit) {}
    ✅ 2
    i
    o
    t
    • 4
    • 45
Powered by Linen
Title
m

Michael Langford

02/09/2022, 9:56 PM
Is there a simple way to execute functions in parallel and wait until all are done? All the examples I find when googling appear to expect a blocking style function instead of already async functions. For instance, I have multiple api endpoints I need to hit, but I don't want to do the model/screen refresh until all 3 have returned. I've simplified the prototype of the functions here a bit for explanatory purposes. I definitely need to call some of these at other times, and don't really want to change their prototype.
fun fetchActivities(userName:String,  completion:(List<ActivityEntry>)->Unit) {}

fun fetchMoves(userName:String,  completion:(List<MoveEntry>)->Unit) {}

fun fetchScores(userName:String,  completion:(List<ScoreEntry>)->Unit) {}
✅ 2
I believe I'm looking for something similar to pthread's barrier, etc.
i

Igor Milakovic

02/09/2022, 10:06 PM
Unfortunately, I don't know for Kotlin, but in iOS/Swift land that would be called
DispatchGroup
, it that helps with googling 🙂
m

Michael Langford

02/09/2022, 10:06 PM
Each of those functions calls Thread.start() btw.
yeah, I know how to do it in swift 😄
😅 1
o

Oliver.O

02/09/2022, 10:07 PM
Coroutines: https://kotlinlang.org/docs/coroutines-basics.html#scope-builder-and-concurrency
m

Michael Langford

02/09/2022, 10:07 PM
That's why I'm trying to keep the pattern to not accidentally mess up some iOS code I'm porting over semantically
I don't have suspending functions that I'm aware of
o

Oliver.O

02/09/2022, 10:11 PM
You can call blocking functions from coroutines. If these are scheduled by the IO dispatcher, blocking won't hurt too much in simple scenarios.
m

Michael Langford

02/09/2022, 10:12 PM
These aren't blocking functions though
o

Oliver.O

02/09/2022, 10:12 PM
What else are they?
m

Michael Langford

02/09/2022, 10:12 PM
fun fetchActivities(userName:String,  completion:(List<ActivityEntry>)->Unit) {
   //   This executes after the network request has completed. 
}
They each have a Thread{do network call stuff}.start()
t

Tim Oltjenbruns

02/09/2022, 10:14 PM
You can wrap a completion style call into coroutines if you want to go that route
take a look at https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/suspend-cancellable-coroutine.html
✅ 1
👍 1
o

Oliver.O

02/09/2022, 10:15 PM
Yep, that's what I was just trying to look up.
m

Michael Langford

02/09/2022, 10:16 PM
oi, thank you. That looks exactly how I can wrap these up.
o

Oliver.O

02/09/2022, 10:16 PM
And then there's
callbackFlow
for more than one result.
t

Tim Oltjenbruns

02/09/2022, 10:17 PM
as for taking your multiple calls and waiting on all of them, this is how I usually do it
listOf(
  async { function1() },
  async { function2() },
  async { function3() }
).awaitAll()
makes it a bit trickier waiting on different return types, so there’s that part to work out. not as simple as I have it above.
m

Michael Langford

02/09/2022, 10:19 PM
yeah, if I don't have all three return values, I get an inconsistent picture of the full state. I know there is some hair there with partial failure, etc. But even how to actually wrap the type of function I have was hard to find, "callback" was the word I was not searching for.
t

Tim Oltjenbruns

02/09/2022, 10:20 PM
makes it tricky coming from iOS where they call callbacks completions!
m

Michael Langford

02/09/2022, 10:21 PM
lol, yeah, indeed. Amusingly, this far more complex multiple callback thingy is only really required on pull to refresh.
is callbackFlow parallelizable?
t

Tim Oltjenbruns

02/09/2022, 10:24 PM
it’s verbose, but it’s the simplest way I can think of to get it done off the top of my head.
val activitiesDeferred = async { activites() }
val movesDeferred = async { moves() }
val scoresDeferred = async { scores() }
val activities = activitiesDeferred.await()
val moves = movesDeferred.await()
val scores = scoresDeferred.await()
callbackflow would be more for returning multiple of the same type
or maybe even a building state that “accumulates” over time
m

Michael Langford

02/09/2022, 10:25 PM
Oh that makes sense
t

Tim Oltjenbruns

02/09/2022, 10:26 PM
data class FullData(
  val activities: Result<List<ActivityEntry>>?,
  val moves: Result<List<MoveEntry>>?,
  val scores: Result<List<ScoreEntry>>?
)
I would only go that route if the intermediate state were valuable to me
because then as your different api calls return, it starts filling out this state and you can action on partial data
If it’s really all or nothing, I’d go with the sadly inelegant first solution of just declaring 3 async’s and awaiting them all individually.
m

Michael Langford

02/09/2022, 10:28 PM
eh, it's only kind of all or nothing
The world is inconsistent if one of the three fails, but they can partially fail, etc.
t

Tim Oltjenbruns

02/09/2022, 10:30 PM
is callbackFlow parallelizable?
It can be but that depends more on the implementation of your Thread situation that happens behind the scenes. A flow can be set on the IO dispatcher which is a big threadpool. But that won’t really matter because you have your own threads inside the implementations
m

Michael Langford

02/09/2022, 10:31 PM
I assumed with your 3 asyncs followed by 3 awaits, the asyncs would each launch their own internal threads, and then the 3 awaits would essentially collect it all
val activitiesDeferred = async { activites() }
val movesDeferred = async { moves() }
val scoresDeferred = async { scores() }
val activities = activitiesDeferred.await()
val moves = movesDeferred.await()
val scores = scoresDeferred.await()
that guy
t

Tim Oltjenbruns

02/09/2022, 10:32 PM
With coroutines each concurrent coroutine is not necessarily it’s own thread.
Coroutines achieves concurrency without multiple threads
But to answer your question, those three async blocks kick off concurrently and eagerly yes. And then the awaits wait until all of them finish
m

Michael Langford

02/09/2022, 10:33 PM
apologies, I didn't mean in general they work that way
I meant "for my particular 3 functions which already go Thread{ doNetworkingStuff() }.start()"
t

Tim Oltjenbruns

02/09/2022, 10:34 PM
Ah yes, so in that situation you have your three threads that kick off, and whatever thread is waiting for them to finish.
The thread that waits for them to finish is determined by what Dispatcher is in the CoroutineScope your
async
block is called from.
m

Michael Langford

02/16/2022, 2:43 PM
Tim: I just want to say, I finally got all the error handling in through your triple async solution, it works gloriously well. Thank you. Its so flexible and works so cleanly. I can handle sub-errors in each decode, partial failures, etc.
View count: 4