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
codingconventions
  • m

    Michael Friend

    02/05/2020, 4:48 PM
    When keep a private property of a mutable data holder but exposing an immutable, is there a functional difference between
    private val _listOfStrings = mutableListOf<String>()
    val listOfStrings : List<String> = _listOfStrings
    // and 
    private val _listOfStrings = mutableListOf<String>()
    val listOfStrings : List<String> 
        get() = _listOfStrings
    Which one is better convention? I like how the first one is more concise but examples often show the second
    d
    b
    • 3
    • 6
  • m

    Michael Friend

    02/07/2020, 3:12 PM
    Whats the opinion of using
    run
    with the elvis operator as a sort of guard statement like in iOS? I’ve wanted a way to do a sort of side effect like logging when using
    ?:
    to exit a function Something like
    fun takesNullables(val string: String?) {
        val notNull = string ?: run {
            println("arg was null")
            return
        }
    }
    
    // Or a more complicated usage 
    fun gaurdTest(val nums: List<Int>, val person: Person) {
        val firstEvent = nums.firstOrNull { it % 2 == 0 } ?: run {
            println("no evens in $nums")
            return
        }
        // Or 
        val streetName = person?.address?.streeName ?: run {
            println("street name not found")
            return
        }
    }
    k
    c
    d
    • 4
    • 3
  • k

    Kroppeb

    02/10/2020, 2:05 PM
    fun addStatement(statement: Statement?){
    	statement?.let{
    		statements.add(it)
    	}
    }
    or less indentation
    fun addStatement(statement: Statement?){
    	statement?:return
    	statements.add(statement)
    }
    or just old reliable
    fun addStatement(statement: Statement?){
    	if(statement != null)
    		statements.add(statement)
    }
    3️⃣ 7
    2️⃣ 2
    1️⃣ 4
    a
    k
    d
    • 4
    • 9
  • n

    Nick Halase

    02/12/2020, 8:02 PM
    What's the most common convention for naming files containing strictly extension functions?
    fooExt.kt
    FooExt.kt
    , etc?
    c
    g
    +2
    • 5
    • 8
  • e

    Ellen Spertus

    02/17/2020, 9:20 PM
    // 1
    fun calculateHour(h: Int, period: String?): Int =
      period?.let {
        when(it) {
          "am" -> if (h == HOURS_PER_PERIOD) 0 else h
          "pm" -> (h % HOURS_PER_PERIOD) + HOURS_PER_PERIOD
          else -> h // should not happen
        }
      } ?: h
    }
    // 2
    fun calculateHour(h: Int, period: String?): Int =
      if (period == null) {
        h
      } else when (period) {
        "am" -> if (h == HOURS_PER_PERIOD) 0 else h
        "pm" -> (h % HOURS_PER_PERIOD) + HOURS_PER_PERIOD
        else -> h // should not happen
      }
    }
    s
    c
    • 3
    • 7
  • d

    dumptruckman

    03/03/2020, 3:25 PM
    I’m struggling to decide on how to deal with this case where I have a method that writes a message to the database without any kind of ORM. The problem is the message has 4+ number of properties (at least sender, timestamp, subject, body) that are required to create one. But in many parts of the code, the row id is going to be desired for this message (something you don’t have until you call the aforementioned method.) Writing a method with 4+ properties is not too awesome, but if I want to create an immutable object to represent this message, how do i create one without having the row id before it’s written to the db? TL;DR for most of the code base I want an immutable message with at least id, sender, timestamp, subject and body, but when creating this message I don’t have the id - I have to first create it in the database. How do I do this in a sane way?
    m
    • 2
    • 6
  • d

    dumptruckman

    03/13/2020, 7:31 PM
    What feels better/more idiomatic?
    val things = getThings() orIfEmpty listOf(SingleThing())
    or
    val things = getThings().letIfEmpty { listOf(SingleThing()) }
    or does someone have a better solution?
    m
    a
    • 3
    • 10
  • d

    dumptruckman

    03/26/2020, 8:36 PM
    From what I remember, the use of the double bang is discouraged. However, I find myself using it a lot to intentionally throw an NPE when something really shouldn’t be null. Example would be a SQL query that should either return no rows or a row with a single column with a non null value. There’s no reason the column should ever be null unless someone changed the DDL of the table at which point the NPE essentially just informs them they have more work to do with such a change. Anyone else experiencing this?
    t
    s
    +2
    • 5
    • 41
  • d

    david.bilik

    03/27/2020, 11:30 AM
    hi is there any convention I should follow when I want to name a function that returns
    Flow
    type? eg. im observing users from database, should i name it like
    fun users() : Flow<List<User>>
    or
    fun observeUsers() : Flow<List<User>>
    or
    fun usersChanges() : Flow<List<User>>
    or 
    fun getUsersStream() : Flow<List<User>>
    ? There is a lot of options and im curious about the best practices
    s
    m
    o
    • 4
    • 9
  • d

    daphillips

    04/01/2020, 12:10 PM
    Which is the better approach for
    name
    ?
    sealed class Things {
        abstract val name: String
    
        data class ThingA(val x: Int, val y: String) : Things() {
            override val name = "foo"
        }
    
        data class ThingB(z: Double) : Things() {
            override val name = "bar"
        }
    }
    or
    sealed class Things(val name: String) {
        data class ThingA(val x: Int, val y: String) : Things("foo")
    
        data class ThingB(z: Double) : Things("bar")
    }
    2️⃣ 1
    m
    t
    • 3
    • 3
  • m

    Michael Pohl

    04/15/2020, 7:33 AM
    When would I prefer the
    .not()
    postfix over the prefix
    !
    for a "is not" check, when not? I can't finda good guideline, and for me personally, the prefixed
    !
    reads easier, but that might just because I'm used to it. Also it's related to
    !=
    which I wouldn't want to repace with
    (a == b).not()
    ...
    e
    • 2
    • 2
  • e

    Ellen Spertus

    05/04/2020, 10:50 PM
    // 1
    override fun onCreateLoader(loaderId: Int, args: Bundle?): Loader<Cursor> {
        val nickname = viewModel.nickname
        return CursorLoader(
            contactActivity,
            ContactsContract.Contacts.CONTENT_URI,
            PROJECTION,
            SELECTION,
            arrayOf(
                nickname, // just the nickname
                "$nickname %", // first name
                "% $nickname", // last name
                "% $nickname %" // middle name
            ),
            null
        )
    }
    or
    // 2
    override fun onCreateLoader(loaderId: Int, args: Bundle?) =
        viewModel.nickname.let { nickname ->
            CursorLoader(
                contactActivity,
                ContactsContract.Contacts.CONTENT_URI,
                PROJECTION,
                SELECTION,
                arrayOf(
                    nickname, // just the nickname
                    "$nickname %", // first name
                    "% $nickname", // last name
                    "% $nickname %" // middle name
                ),
                null
            )
        }
    1️⃣ 7
    m
    g
    • 3
    • 4
  • s

    sindrenm

    05/07/2020, 9:29 AM
    Given
    val string: String? = "possibly-null"
    Which of the following do people prefer to get either the value or an empty string if it's null?
    val stringOrEmpty: String = string ?: ""
    1️⃣ or
    val stringOrEmpty: String = string.orEmpty()
    2️⃣
    1️⃣ 2
    2️⃣ 12
    m
    m
    • 3
    • 5
  • d

    Dmitry Kandalov

    05/15/2020, 9:57 AM
    What is your preferred name for an extension function which is essentially a local version of 
    .toString()
     but you can’t call it “toString” because it’s shadowed by 
    Object#toString
    ?
    e
    • 2
    • 2
  • j

    JP

    05/23/2020, 2:20 PM
    Which convention is better? 1.
    checkNotNull(x).also {
        // do something like..
        it.prop = y
        // ...
    }
    2.
    x?.apply {
        // do something like..
        it.prop = y
        // ...
    } ?: throw IllegalStateException()
    b
    o
    • 3
    • 6
  • b

    bsimmons

    07/27/2020, 12:46 PM
    Does anyone have any thoughts about always putting a space before a lambda? It seems to me like there should be no space as to make it similar to function call syntax?
    // Why is it that we are encouraged to add spaces before EVERY lambda?
    // Seems to me like the spaces arbitrarily break up this expression.
    list.filter { it < 10 }.map { it * it }
    
    // This is the long-form syntax, right?
    list.filter({ it < 10 }).map({ it * it })
    
    // So after a little syntactic sugar, we should end up like this?
    list.filter{ it < 10 }.map{ it * it }
    t
    k
    +2
    • 5
    • 16
  • f

    Fabian Braun

    08/03/2020, 10:15 AM
    Local variables vs. Scope functions (
    .let
    in particular)
    Sometimes I have a hard time to decide about when to use
    .let
    and when local variables should be preferred. Consider the example from https://kotlinlang.org/docs/reference/scope-functions.html#let which reads like:
    val numbers = listOf("one", "two", "three", "four")
    val modifiedFirstItem = numbers.first().let { firstItem ->
        println("The first item of the list is '$firstItem'")
        if (firstItem.length >= 5) firstItem else "!" + firstItem + "!"
    }.toUpperCase()
    println("First item after modifications: '$modifiedFirstItem'")
    It could be rewritten to:
    val numbers = listOf("one", "two", "three", "four")
    numbers.first().let { firstItem ->
       	println("The first item of the list is '$firstItem'")
       	if (firstItem.length >= 5) firstItem else "!" + firstItem + "!"
    }.toUpperCase().let { modifiedFirstItem ->
    	println("First item after modifications: '$modifiedFirstItem'")        
    }
    However, in my opinion the second
    .let
    makes the code less readable in this second snippet. I have heard people say that local variables are not good kotlin-style and you should be using scope-functions but I couldn’t find any resources for that claim. Would be grateful for style-recommendations / resources on that.
    g
    t
    a
    • 4
    • 12
  • s

    Sam

    08/14/2020, 3:09 AM
    Good morning. How can I automatically appear blue params without having to re-type? Thanks
    m
    • 2
    • 2
  • m

    Marc Knaup

    08/22/2020, 2:11 PM
    Factory function, companion function or extension function? 🤔 1️⃣
    fun CurrencyCode(value: String): CurrencyCode         // throws if invalid
    fun CurrencyCodeOrNull(value: String): CurrencyCode?  // null if invalid
    2️⃣
    fun CurrencyCode.Companion.parse(value: String): CurrencyCode         // throws if invalid
    fun CurrencyCode.Companion.parseOrNull(value: String): CurrencyCode?  // null if invalid
    3️⃣
    fun String.toCurrencyCode(): CurrencyCode         // throws if invalid
    fun String.toCurrencyCodeOrNull(): CurrencyCode?  // null if invalid
    1️⃣ 1
    3️⃣ 7
    2️⃣ 7
    e
    • 2
    • 1
  • a

    agu

    08/22/2020, 9:26 PM
    Hi, which is the kotlin's approach to composing actions that may fail? Of course the actions may be suspended. I come from scala, so the "alternative" to
    Either
    alongside with
    Future
    and the
    map
    function. I've watched the presentations of Elizarov (which are excellent by the way), but couldn't imagine how to replace the
    Either
    . Thanks in advance.
    t
    m
    • 3
    • 5
  • m

    Marc Knaup

    09/01/2020, 2:23 PM
    Is there a more idiomatic way than aborting a loop if needed and returning
    null
    if it completes?
    interface Foo
    interface FooProvider { fun provide(): Foo? }
    
    fun provideFoo(providers: List<FooProvider>): Foo? {
    	for (provider in providers)
    		provider.provide()?.let { return it }
    
    	return null
    }
    I miss something like
    providers.firstNonNullMapped { it.provide() }
    (and with a better name).
    a
    s
    +3
    • 6
    • 7
  • c

    Czar

    09/04/2020, 10:45 AM
    does the new recommended style of star-import everything cause problems for others as well? E.g. I was just now migrating an app to ktor 1.4 and kotlinx serialization 1.0-RC and wasted like 10 minutes trying to fix
    Json {}
    builder, until I noticed that intellij imported wrong class via star import before I got to Json {}. After this I'm reverting the style config, star imports are evil and when one wants them, this needs to be explicit. It was quite unexpected when JB introduced the convention. I did give it a chance, but nope,
    import bla.bla.*
    default was evil, is evil and probably will remain so while imports exist 🙂
    ☝️ 3
    s
    m
    e
    • 4
    • 3
  • m

    Marc Knaup

    10/13/2020, 12:12 AM
    When it comes to “entity”-like objects there are typically two kinds of implementation for `equals`: • both objects refer to the same entity (
    a.id == b.id
    ) • both entities are completely equal (
    a.id == b.id && a.prop1 == b.prop1 && …
    ) I can’t decide whether I should implement
    equals
    as comparing merely IDs or comparing entire entities. 1️⃣ Equality by entity IDs • If compare IDs I cover common cases like
    if (sender != recipient) sendNotification(…)
    and it reads very natural. • It’s also more performant because in most cases you don’t need to compare entire entities. • For
    Set<Entity>
    typically also the ID is compared, meaning you want to have one entry per user and not one entry per “state” per user. • This can be confusing however if the entity is using
    data class
    . Most developer would expect by-property equality for data classes. 2️⃣ Equality by entity properties • If I compare entire entities I can do neat things like checking if datasets have changed. If I have a
    val old: Collection<User>
    and
    val new: Collection<User>
    and want to check if there have been any updates between the two I can simply use
    old != new
    . That’s useful for example for Flows and
    distinctUntilChanged()
    . • Developers may however run into unexpected behavior if for some reason
    sender
    and
    recipient
    refer to the same user (by ID) but one of the two instances has slightly different properties (e.g. due to a prior update). Because
    sender != recipient
    reads so natural, that can be very unexpected. There is a third option where you use either 1️⃣ or 2️⃣ and provide the other one as an additional entity function. That gets tricky however when you’re in a generic context and may not know enough about the type to call such a function, e.g. in a
    Flow<Collection<T>>.distinctUntilChanged { old, new -> … }
    . I’m curious, how do you usually do that in your codebases?
    2️⃣ 5
    1️⃣ 1
    t
    m
    • 3
    • 2
  • d

    diego-gomez-olvera

    10/13/2020, 4:07 PM
    I recall a discussion in the past about using function expression (
    =
    ) with
    Unit
    . In general I favor avoiding this and other people also found it confusing. Do you know if there is any kind of official guideline about it? https://kotlinlang.slack.com/archives/C4GKV43N2/p1506416194000224
    f
    r
    • 3
    • 4
  • d

    Dmitry Kandalov

    10/14/2020, 10:12 PM
    What is the “best” way to format chained infix functions? For example, there is an infix
    or
    function and I want to write something like this:
    val json =
        obj or
        array or
        string or
        number
    However, IDE formats it as:
    val json =
        obj or
            array or
            string or
            number
    And one line can be hard to read for a long list of chained functions:
    val json = obj or array or string or number
    e
    • 2
    • 3
  • k

    KV

    10/23/2020, 5:49 AM
    what is the the best way to write the below code? In the below code I have 9 buttons but wha if I have more then 9 button and set the text to all the buttons. Do we have any simpler way to write this method?
    private fun setupPinKeypad() {
            binding.pinCodeLayout.btn0.text = ZERO.toString()
            binding.pinCodeLayout.btn1.text = ONE.toString()
            binding.pinCodeLayout.btn2.text = TWO.toString()
            binding.pinCodeLayout.btn3.text = THREE.toString()
            binding.pinCodeLayout.btn4.text = FOUR.toString()
            binding.pinCodeLayout.btn5.text = FIVE.toString()
            binding.pinCodeLayout.btn6.text = SIX.toString()
            binding.pinCodeLayout.btn7.text = SEVEN.toString()
            binding.pinCodeLayout.btn8.text = EIGHT.toString()
            binding.pinCodeLayout.btn9.text = NINE.toString()
        }
    g
    m
    • 3
    • 11
  • k

    KV

    10/28/2020, 4:25 AM
    What is the best way to right the code? I have one variable like this ->
    val filter: QueryFilter? = null
    and I have one class like this ->
    class QueryFilter(val by: String, val operator: String, val value: String)
    And I am using the variable with class like this ->
    filter.let {
                        mapOf(Pair("q[${<http://it.by|it.by>}_${it.operator}]", it.value))
                    } ?: emptyMap()
    But now I have a variable like this
    val filter: Array<QueryFilter> = emptyArray()
    then how to use the loop with filter function with the same class? I want to know that is this the correct way to write a code ? or Is there any better way to write the below code?
    filter.let { it ->
                        it.forEach {
                            mapOf(Pair("q[${<http://it.by|it.by>}_${it.operator}]", it.value))
                        }
                    }
                }) as Map<String, String>
    t
    • 2
    • 7
  • c

    Chris Black

    10/30/2020, 4:26 PM
    Is there a “better” way to write this
    create
    function?
    fun add(vararg s: String): String =
        s.joinToString(" ")
    
    fun create(one: String, two: String, three: String): String {
        val m = mapOf(
            one to "one case",
            two to "two case",
            three to "three case",
            "" to ""
        )
        return add(m[one]!!, m[two]!!, m[three]!!)
    }
    e
    m
    • 3
    • 6
  • o

    orafaaraujo

    11/18/2020, 6:05 PM
    Hello, I remember something about avoiding the usage
    when
    when you can go with a simple
    if
    But I can’t find it now… Does anyone knows where is it?
    m
    a
    s
    • 4
    • 13
  • m

    Manuel Wrage

    11/20/2020, 8:36 AM
    Is there a good naming convention for this?
    fun doSomething()
    suspend fun doSomethingSuspending()
    e
    • 2
    • 6
Powered by Linen
Title
m

Manuel Wrage

11/20/2020, 8:36 AM
Is there a good naming convention for this?
fun doSomething()
suspend fun doSomethingSuspending()
e

elizarov

11/20/2020, 9:31 AM
suspend fun doSomething()
fun doSomethingBlocking()
👍 13
Rationale:
Blocking
variant is more dangerous and, what's worse, can be called from anywhere (by mistake), so it must have a longer name
➕ 7
m

Manuel Wrage

11/20/2020, 9:34 AM
Ok and what if i have something like this
// fire and forget
fun dispatch(action: Action)
// dispatches the action and suspends until consumed
suspend fun dispatchSuspend(action: Action)
As an alternative i could do this?
fun dispatch(action: Action): Deferred<Unit>
e

elizarov

11/20/2020, 9:51 AM
That's a totally different story. In this case use different verbs or invent some other way to differentiate between them. In the latter case cal the function
dispatchAsync
to highlight the fact that it only starts the action, but does not wait for its completion in any way.
m

Manuel Wrage

11/20/2020, 4:27 PM
Ok thanks.
View count: 2