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

    Ellen Spertus

    05/10/2022, 6:27 PM
    I'm reviewing some Kotlin code, and the KDoc comments look like this:
    /**
     * Blah blah blah.
     * */
    Is the close to the comment "`* */`" something you've seen in the wild? The documentation shows "`*/`". https://kotlinlang.org/docs/kotlin-doc.html#generate-the-documentation
    m
    • 2
    • 1
  • j

    Jonathan Olsson

    05/13/2022, 12:45 PM
    Is it considered an OK practice to rely on
    toString()
    for non-debugging/non-logging purposes in a situation like this:
    value class AccessToken(private val s: String) {
        override fun toString(): String = s
    }
    
    val header = "Bearer $accessToken"
    Given that inline classes most often wrap primitive-ish types, in my mind it falls into the same category as
    Long.MIN_VALUE.toString()
    . Wdyt?
    f
    s
    e
    • 4
    • 8
  • e

    Ellen Spertus

    05/14/2022, 9:04 PM
    Is there a more elegant way to do something like this:
    fun getSomething(): SomeType {
       val result = computeSomething()
       doSomethingElse()
       return result
    }
    :yes: 2
    s
    s
    j
    • 4
    • 4
  • v

    Vivek Modi

    06/01/2022, 2:19 PM
    Hey I have object of
    Event
    . I want to combine all property value into single string. I did this without any problem. I want to know is there any better way to optimise this code in memory, efficiency etc. SingleEventString.kt
    fun main() {
            var newString: String? = null
            val eventList = createData()
            eventList.forEachIndexed { index, event ->
                val title = event.title
                val status = event.status
                if (!title.isNullOrEmpty()) {
                    newString = if(index == 0){
                        "$title"
                    }else{
                        "$newString $title"
                    }
                }
                if (!status.isNullOrEmpty()) {
                    newString = "$newString $status"
                }
            }
            println(newString)
        }
        
        data class Event(val title: String? = null, val status: String? = null)
        
        fun createData() = listOf(
            Event("text 1", "abc"),
            Event("text 2", "abc"),
            Event("text 3", "abc"),
            Event("text 4", "abc"),
            Event("", "abc"),
            Event(null, "abc")
    )
    s
    l
    +2
    • 5
    • 22
  • m

    Mark

    06/02/2022, 2:42 PM
    I’m curious regarding the naming conventions behind having
    toList()
    but then
    asSequence()
    instead of
    toSequence()
    ?
    j
    e
    n
    • 4
    • 15
  • k

    Klitos Kyriacou

    06/16/2022, 4:46 PM
    What would be a good package & file name for a set of String utility functions (top-level functions, some extensions, some non-extensions). I've used
    package companyname.productname.utils
    and filename
    Strings.kt
    but I'm looking for something more meaningful, descriptive and idiomatic.
    y
    g
    • 3
    • 4
  • v

    vqrs

    07/15/2022, 8:39 AM
    How do you name DSL context receivers? E.g. in
    dsl(block: THIS.() -> Unit)
    Do you consistently name it
    *Scope
    ,
    *Ctx
    or something to that extent?
    y
    • 2
    • 1
  • j

    Jonathan Ellis

    07/21/2022, 1:40 PM
    'capitalize(): String' is deprecated. Use replaceFirstChar instead
    what is the thinking here?
    replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
    is a lot clunkier
    😕 1
    m
    m
    +2
    • 5
    • 18
  • e

    ephemient

    07/26/2022, 5:22 PM
    as long as it is written like that (and not
    val range = 1..12; return month in range
    ), then the compiler does not create the IntRange and produces code equivalent to the first
    j
    • 2
    • 1
  • s

    Slackbot

    07/28/2022, 4:02 PM
    This message was deleted.
  • k

    Klitos Kyriacou

    08/10/2022, 10:36 AM
    I wrote a function that returns a
    kotlin.Result
    . The project I'm working on currently uses Kotlin 1.6.21, and IDEA 2022.1 tells me "Function returning Result with a name that does not end with Catching". Is this a recommended coding convention? What is the disadvantage of not ending in "Catching"? Also, when I click on "Show inspection description", it says "Result should never be used as a return type." I know that was the case in an old version of Kotlin, when the Result type was first introduced, but I thought that was now changed and that we can now return Result. Is this something that should be changed in IDEA?
    g
    • 2
    • 2
  • s

    Sam Stone

    08/12/2022, 8:56 PM
    A corollary to this is when to use top level classes vs. nested classes.
    e
    k
    • 3
    • 6
  • g

    George

    08/20/2022, 12:13 PM
    Hi folks, not sure if my question is for this channel so feel free to point me to the right one 🙂 . I am browsing some code from kotlinx.coroutines and kotlin.serialization libraries and i have observed that the jet-team rarely-ish uses space between code, for example: to group different bs-logics., etc etc. Anyone knows the whys?, feel free to point me to books, docs, blogs etc and thanks for any answers in advance !
    m
    • 2
    • 6
  • b

    Ben Edwards

    08/24/2022, 12:07 PM
    In my past I have it in my head that is is good practice just to have one return in a function so rather than do
    *fun* dropLoot(name: String): Boolean {
    *for* (item *in inventory*) {
    *if* (item.*name* == name) {
    *inventory*.remove(item)
    return true
    }
    }
    return false
    }
    I would do
    *fun* dropLoot(name: String): Boolean {
    *var* ret = *false*
    *for* (item *in inventory*) {
    *if* (item.*name* == name) {
    *inventory*.remove(item)
    ret = *true*
    break
    }
    *return* ret
    }
    What do people think?
    m
    a
    +2
    • 5
    • 18
  • s

    sreich

    09/01/2022, 6:52 PM
    what is the standard for enums and static vars, regarding casing. In java it is DARK_CHOCOLATE vs darkChocolate for example
    l
    m
    • 3
    • 4
  • s

    sreich

    09/12/2022, 6:46 PM
    i've noticed the
    isEnabled
    convention in java land. i am assuming in kotlin it would just be
    enabled
    , am i correct in this? i can't remember the justification people had for doing that in java, sth to do with properties?
    e
    • 2
    • 4
  • g

    George

    10/05/2022, 8:45 AM
    Hi folks,
    class ServerError private constructor(val message: String, val code: Int) {
        fun <T> toErrorPayload(): HubPayload<T> = errorPayload(message, code)
    }
    In this case the function
    toErrorPayload
    (for the sake of example ignore the HubPayload return type :)) naming prefix convention shouldBe
    to
    or
    as
    . Since im returning another object i guess the default is
    to
    , but if i want to emphasize that the values remain the same, just the wrapper is changing then should i name it
    asErrorPayload
    ? Thanks in advance for any answers !
    j
    p
    • 3
    • 3
  • s

    Sam Stone

    11/06/2022, 1:31 AM
    In a function like
    equals
    , when should you use
    if(condition) { return true } else {}
    and when should you leave out the else, and use implicit flow control (it is by definition else because it didn’t return). Is there a performance impact in including
    else
    ?
    c
    e
    e
    • 4
    • 9
  • e

    Ellen Spertus

    11/06/2022, 9:53 PM
    I could use some guidance on when to place code in a companion objects vs. at the top level. For example, I have:
    class WordleGame(val secretWord: String) {
      // lots of stuff in here pertaining to a single game of Wordle.
      val guesses = mutableListOf<String>()
    
      fun guessWord(guess: String): String {
        ...
      }
    }
    
    fun playGame() {
      // Load dictionary.
      val wordleGame = WordleGame(dictionary.random())
      // Solicit guesses from user and feed them to game object, etc.
    }
    Should
    playGame()
    be in a
    companion object
    in
    WordleGame
    ? It certainly would be a handy place to keep the dictionary.
    c
    • 2
    • 1
  • a

    Adam Cooper

    11/07/2022, 10:39 PM
    I read an article about how it is better to return a
    Result
    than throw an exception. Is that true in all cases? I've found from my experience in other languages that it's a lot easier to write a REST API with some type of special HTTP status exception that you can throw, which will be handled at the top level and respond appropriately to the client. Should libraries use exceptions? I haven't seen any libraries which return `Result`s.
    j
    j
    +3
    • 6
    • 45
  • g

    George

    11/10/2022, 3:10 PM
    Hello folks, after reading this article from roman: https://elizarov.medium.com/kotlin-and-exceptions-8062f589d07 i have a question: On the section about input/output particular, since the example is:
    fun updateOrderQuanity(orderId: OrderId, quantity: Int) {
        require(quantity > 0) { "Quantity must be positive" }
        val order = loadOrder(orderId)
        order.quantity = quantity
        storeOrder(order)
    }
    It is safe to assume that when we are creating a top-level-handler
    Dedicate a single top-level place in your code to address all network errors uniformly
    Here we actual also refer to
    IOExceptions
    and
    IllegalArgumentExceptions
    (and any other input/output exceptions)? Thanks in advance for any answers !
    • 1
    • 1
  • e

    Ellen Spertus

    11/19/2022, 12:56 AM
    I'm fine with putting anonymous functions outside the parentheses when passing them to a function like
    filter
    , but it seems strange in this situation. What do you think?
    Untitled.cpp
    p
    • 2
    • 3
  • s

    Sam Stone

    11/23/2022, 5:55 AM
    What is the best way (for performance and readability) to check for multiple equalities? Option 1:
    if(string !in arrayOf("str1", "str2", "str3"...)) foo()
    Option 2:
    if(string != "str1" && string != "str2" ...) foo()
    Option 3:
    when(string)  { "str1", "str2", "str3" -> {} else -> foo())
    The bytecode for option 3 uses `string`’s hashcode in something like:
    label20: {
             switch(string.hashCode()) {
                case 3541024:
                   if (string.equals("str1")) {
                      break label20;
                   }
                   break;
                case 3541025:
                   if (string.equals("str2")) {
                      break label20;
                   }
                   break;
                case 3541026:
                   if (string.equals("str3")) {
                     break label20;
                   }
                }
            foo()
    }
    e
    r
    +5
    • 8
    • 15
  • g

    George

    11/30/2022, 2:44 PM
    How much ok is it to use Any in general application code to represent a union? Use-case: return either a dto or a sealed class. End-goal is to simplify the function and chop it in smaller pieces but probably this will no simplify it at all 😛 Thanks in advance for any answers!!
    c
    j
    +2
    • 5
    • 29
  • s

    Slackbot

    12/06/2022, 5:38 AM
    This message was deleted.
    r
    • 2
    • 1
  • s

    Seokjae Lee

    12/31/2022, 11:19 AM
    Hello 🙂, Is there a style guide or convention for how to declare an
    infix function
    ? I wonder what is the officially recommended method, or what is the most used method? 1.
    infix fun Class.test(something: Something): Class = this.test(something)
    2.
    infix fun Class.test(something: Something): Class = test(something)
    3.
    infix fun Class. test(something: Something): Class { return this. test(something) }
    4.
    infix fun Class.test(something: Something): Class { return test(something) }
  • g

    George

    01/03/2023, 10:42 AM
    Im browsing a bit the code from Result.kt in stdlib. Im wondering how come
    runCatching()
    does not catch
    Exception
    instead of
    Throwable
    ? Shouldn't we always let errors such as
    StackOverflow
    be thrown ?
    p
    • 2
    • 2
  • k

    Klitos Kyriacou

    01/09/2023, 11:36 AM
    What's the most conventional indenting scheme with multiline blocks? I've seen these: 1:
    val statement = connection.prepareStatement(
        """
        UPDATE tablename
        SET column1 = ?
        WHERE column2 = ?
        """.trimIndent()
    )
    2:
    val statement = connection.prepareStatement("""
            UPDATE tablename
            SET column1 = ?
            WHERE column2 = ?
        """.trimIndent()
    )
    and various others.
    m
    • 2
    • 1
  • n

    Nick Halase

    03/02/2023, 9:28 PM
    How do you guys write
    error(message: String)
    messages? 1.
    System.getenv("GITHUB_SHA") ?: error("GITHUB_SHA is missing")
    2.
    System.getenv("GITHUB_SHA") ?: error("GITHUB_SHA must exist")
    d
    e
    +3
    • 6
    • 11
  • g

    groostav

    03/15/2023, 9:48 PM
    regarding a large codebase needing good java interop, thoughts on the function signature
    class ConvertedOldModelObject private constructor(oldCtorArg: OldJavaDomainType, ...) {
      //...
      companion object {
        @JvmStatic @JvmName("create") operator fun invoke(oldCtorArg: OldJavaDomainType, ...) {
          //some caching logic to try to avoid hanging on to allocaitons, a kind of poor mans constant pool
    
          return CovertedOldModelObject(oldCtorArg, cachedArgs, ...)
        }
      }
    }
    pros: • I get
    OldJavaDomainType oldThing = OldJavaDomainType.create(args...)
    from java • I get
    val x = OldJavaDomainType(args...)
    from kotlin cons: •
    companion object operator fun invoke
    seems like a kind of nifty hack, not sure how somebody else would feel stumbling across it • reasonable alternatives like simply offering a global function for kotlin and a simpler
    fun create()
    method for java seems sufficient, though slightly bloatier
    e
    y
    • 3
    • 4
Powered by Linen
Title
g

groostav

03/15/2023, 9:48 PM
regarding a large codebase needing good java interop, thoughts on the function signature
class ConvertedOldModelObject private constructor(oldCtorArg: OldJavaDomainType, ...) {
  //...
  companion object {
    @JvmStatic @JvmName("create") operator fun invoke(oldCtorArg: OldJavaDomainType, ...) {
      //some caching logic to try to avoid hanging on to allocaitons, a kind of poor mans constant pool

      return CovertedOldModelObject(oldCtorArg, cachedArgs, ...)
    }
  }
}
pros: • I get
OldJavaDomainType oldThing = OldJavaDomainType.create(args...)
from java • I get
val x = OldJavaDomainType(args...)
from kotlin cons: •
companion object operator fun invoke
seems like a kind of nifty hack, not sure how somebody else would feel stumbling across it • reasonable alternatives like simply offering a global function for kotlin and a simpler
fun create()
method for java seems sufficient, though slightly bloatier
e

ephemient

03/15/2023, 10:16 PM
pooling is generally a bad idea in modern JVMs (and even Android ART)
any sort of thread safety will be slower than simply getting new objects from the bump allocator and letting GC clean them up
as for the API itself, the
companion object { operator invoke() }
trick is fine. overall I think it's more common in Kotlin to use
interface Foo
private class FooImpl(...) : Foo
public fun Foo(...): Foo = FooImpl(...)
but that doesn't lead to the same Java API
y

Youssef Shoaib [MOD]

03/16/2023, 10:12 AM
companion object operator fun invoke
is definitely idiomatic Kotlin, but yes sometimes people just have a top-level function with the class name. Personally, I think here it makes the most sense to use a companion object so that you get the wanted experience from Java
View count: 5