https://kotlinlang.org logo
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
benchmarks
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
confetti
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
hiring-french
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
lincheck
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
Title
w

Waldemar Kornewald

05/16/2023, 12:41 PM
Not sure if this is the best channel to ask, but does anyone know some compiler plugin which can turn a class with suspend (or non-suspend) functions and also a whole module or individual functions into non-suspend (or suspend) versions, so one doesn’t have to copy-paste lots of code and keep the two versions in sync by hand? The function coloring problem keeps hitting us every now and then and
inline
can’t always be used to work around it.
e

efemoney

05/16/2023, 3:38 PM
What function coloring problem and how does inline work around it?? Can you post a code example?
w

Waldemar Kornewald

05/17/2023, 6:10 AM
With the “function coloring problem” I was referring to the post by Bob Nystrom which received some attention: https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/ Basically, the core issue is the infectiousness of
suspend
(or
async
), i.e. it infects the caller which now also has to use
suspend
or at least
launch
. This means your code gets split into two incompatible worlds and you need to duplicate code under different names to make it usable for both worlds. Infectiousness of any kind is always bad (there are also architectural decisions which lead to infectious patterns). For instance, I’ve written a parser library, but it’s not using
suspend
because it needs to be usable without coroutines. Now I need the same API for streaming parsing and the most natural solution would be to use
suspend
. I don’t want to duplicate all that code because this risks introducing too many bugs/inconsistencies during maintenance. It’s a mostly mechanical transformation that the compiler could do for me. Or at least a compiler plugin could help. With
inline
you can partially work around this:
inline fun foo(block: () -> Unit) { ... }
Although you didn’t declare
foo
and
block
as
suspend
the
inline
makes them compatible. So you can call
foo { synchronousCall() }
but also
foo { suspendCall() }
. The compiler will do the right thing and turn
foo
into a
suspend
function only when needed while in all other cases it’s a synchronous non-suspend function. Ideally, the compiler would be able to do this with every function and we could get rid of
suspend
completely.
e

efemoney

05/17/2023, 10:33 AM
This means your code gets split into two incompatible worlds
Your code is already in two incompatible worlds.
suspend fun
means this function can “suspend” execution of its caller while it does its work. It comes with many concepts but that basic one is the building block for ALL coroutines. normal
fun
cannot and will not have the same behavior. You cannot model what
suspend fun
model using normal functions.
For instance, I’ve written a parser library, but it’s not using
suspend
because it needs to be usable without coroutines. Now I need the same API for streaming parsing and the most natural solution would be to use
suspend
Which brings me to this part. You’ve written a blocking parser library. The natural solution is actually not to duplicate the API & implement streaming in coroutines but to implement streaming using blocking code just like you have the base API. You cannot have non-blocking (suspendable) code with an API that is blocking. Normal functions just cannot model suspendable computations.
With
inline
you can partially work around this:
This is a complete misconstruing of what
inline
does. It’s simple and should not be taken to mean anything other than what it does which is inline its function body at the call site! Basically the body of the function runs within the context of the caller. If that is a suspendable context then the body of the inlined lambda can call suspend functions. If the context is not suspendable then you cannot call suspend functions. It is not a way to workaround anything neither does it make two incompatible things compatible.
The compiler will do the right thing and turn
foo
into a
suspend
function only when needed while in all other cases it’s a synchronous non-suspend function.
No. The compiler does no such thing. See screen shot, if
foo
“_*became suspendable*_” via compiler magic, it will have a suspend icon in the gutter beside line number 6 but it doesnt because it is neither a normal function nor a suspend function. Its an inline function with defined semantics.
w

Waldemar Kornewald

05/17/2023, 11:10 AM
Your code is already in two incompatible worlds.
suspend fun
means this function can “suspend” execution of its caller while it does its work. It comes with many concepts but that basic one is the building block for ALL coroutines.
normal
fun
cannot and will not have the same behavior. You cannot model what
suspend fun
model using normal functions.
That’s not true. This is just a limitation of the language. The compiler could solve this automatically, but it would be more effort and maybe slower to analyze. At the very least you can solve it like in Java’s Project Loom or Go. There you don’t have this two worlds problem. The two worlds problem is not a fundamental limitation of asynchronous programming. It’s only a limitation of the Kotlin approach.
Which brings me to this part. You’ve written a blocking parser library. The natural solution is actually not to duplicate the API & implement streaming in coroutines but to implement streaming using blocking code just like you have the base API. You cannot have non-blocking (suspendable) code with an API that is blocking. Normal functions just cannot model suspendable computations
I want to have a very natural API for the parser which is on par with PEGs, but is just normal Kotlin code. The blocking version already achieves this goal. By putting
suspend
everywhere I can keep the natural API and make it non-blocking. What’s your alternative suggestion? I don’t want to have RxJava-style operator chains like the other parser libraries because then the code becomes ugly and limited.
This is a complete misconstruing of what
inline
does. It’s simple and should not be taken to mean anything other than what it does which is inline its function body at the call site! Basically the body of the function runs within the context of the caller. If that is a suspendable context then the body of the inlined lambda can call suspend functions. If the context is not suspendable then you cannot call suspend functions. It is not a way to workaround anything neither does it make two incompatible things compatible.
I know what
inline
really means. However, even in the stdlib Kotlin uses
inline
in a lot of places which look a lot like they were chosen on purpose to be compatible with both suspend and non-suspend. And it’s the only real workaround for making functions work in both worlds. That’s why I mentioned inline.
No. The compiler does no such thing. See screen shot, if
foo
“_*became suspendable*_” via compiler magic, it will have a suspend icon in the gutter beside line number 6 but it doesnt because it is neither a normal function nor a suspend function. Its an inline function with defined semantics.
The compiler simply inlines the block. The function foo doesn’t really exist anymore after inlining, so from a pedantic point of view foo doesn’t become suspendable because there is no foo at all. However, the point is that you can use
foo
with
sus
even though
foo
is not marked as
suspend
. So from a practical point of view, foo is really compatible with two worlds only because it uses
inline
. This is exactly what I said right from the start.