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

    Ellen Spertus

    01/09/2021, 12:34 AM
    Android Studio doesn't
    rollButton.text = "Press"
    , as shown by the underscore under `text`:
    g
    • 2
    • 5
  • p

    pawegio

    02/03/2021, 3:44 PM
    I think I started overusing trailing commas in Kotlin using them wherever I might benefit from shorter diffs in the future. What are your rules to limit trailing commas, keeping codebase clean?
    e
    m
    • 3
    • 2
  • e

    Ellen Spertus

    02/17/2021, 9:26 PM
    Which do you like better? 1️⃣
    boxes.forEach {
        it.setOnClickListener { 
            makeColored(it) 
        }
    }
    2️⃣
    boxes.forEach { it.setOnClickListener { makeColored(it) } }
    3️⃣ @Marc Knaup
    boxes.forEach { it.setOnClickListener(::makeColored) }
    4️⃣ @ephemient
    for (box in boxes) {
        box.setOnClickListener { makeColored(it) }
    }
    5️⃣ @Marc Knaup @ephemient
    for (box in boxes) {
        box.setOnClickListener(::makeColored)
    }
    1️⃣ 1
    3️⃣ 17
    5️⃣ 8
    m
    e
    +2
    • 5
    • 12
  • a

    arekolek

    03/04/2021, 1:57 PM
    listOf(1, 2, 3).map { Unit }
    IDE marks
    Unit
    as redundant and proposes to replace it with:
    listOf(1, 2, 3).map { }
    How do you handle this? Proposed fix looks weird to me. This issue occurs quite often in RxJava streams
    c
    m
    g
    • 4
    • 6
  • d

    diego-gomez-olvera

    03/05/2021, 1:33 PM
    I find the trailing commas convenient for the multi-line declarations, but also a bit strange on method calls. I wonder if they are commonly used (👍 for yes, 👎 for no), and in which cases https://twitter.com/dankim/status/1367602098985201671
    👍 13
    👎 2
    c
    m
    +2
    • 5
    • 12
  • s

    Shawn

    03/05/2021, 4:10 PM
    I’ve literally never understood this.
    val foo = Foo(
        bar,
        baz,
        qux
    )
    “so readable” “looks right” “as god intended”
    val foo = Foo(
        bar,
        baz,
        qux,
    )
    “ew gross” “_literally_ unreadable” “`parse error: Expected another key-value pair`”
    😆 6
    c
    k
    +3
    • 6
    • 8
  • m

    miqbaldc

    04/02/2021, 5:50 AM
    any suggestion to improves below code?
    data class State(title: String, description: String)
    
    fun State.toSessionExpired(): State {
        val state = this
        return with(state) {
            // when token expired
            if (httpCode == 401) {
               copy(
                   title = getString(R.string.error_expired_title),
                   description = getString(R.string.error_expired_description),
               )
            } else this
       }
    }
    a
    e
    t
    • 4
    • 13
  • t

    therealbluepandabear

    04/09/2021, 5:40 AM
    First or second:
    val notificationHelper: INotificationHelper = NotificationHelper(this)
    val notificationHelperTwo = NotificationHelper(this)
    2️⃣ 6
    e
    y
    +2
    • 5
    • 22
  • t

    therealbluepandabear

    04/11/2021, 11:36 PM
    First or second?
    startActivityForResult(
        CheatActivity.newIntent(this@MainActivity, quizViewModel.currentQuestionAnswer),
        REQUEST_CODE_CHEAT,
        ActivityOptions.makeCustomAnimation(
            this,
            R.anim.fragment_fade_enter,
            R.anim.fragment_fade_exit
        ).toBundle()
    )
    val intent = CheatActivity.newIntent(this@MainActivity, quizViewModel.currentQuestionAnswer)
    val animation = ActivityOptions.makeCustomAnimation(this, R.anim.fragment_fade_enter, R.anim.fragment_fade_exit).toBundle()
    startActivityForResult(intent, REQUEST_CODE_CHEAT, animation)
    e
    m
    • 3
    • 14
  • m

    Mark

    04/12/2021, 2:27 AM
    When declaring a higher order function (that accepts a lambda as argument) where you don’t use (and don’t care about) the return value of the lambda, do you put
    Any?
    or
    Unit
    for the return type? I guess
    Any?
    is the appropriate type, but I wonder if it adds confusion for example in private functions where you know the return type of the lambda is always
    Unit
    . 1.
    Any?
    always 2.
    Unit
    always 3.
    Any?
    when public,
    Unit
    when private and possible
    2️⃣ 6
    t
    e
    • 3
    • 5
  • m

    Matteo Mirk

    04/20/2021, 3:00 PM
    When translating a class’ static factory methods from Java (used to construct its instances, not the Factory pattern), what do you prefer to use and why? 1️⃣ companion object 2️⃣ top-level function At first [1] seems a direct translation and will be familiar to Java devs, while [2] gives the possibility to escape the class definition and even the same file (although extension function offer the latter benefit as well). What do you think feels more idiomatic Kotlin?
    2️⃣ 2
    1️⃣ 1
    e
    m
    • 3
    • 9
  • t

    Tomasz Krakowiak

    04/21/2021, 4:59 PM
    When designing a API, what principles should I follow to choose whether given type should be SAM or typealias for a function type?
    j
    r
    • 3
    • 9
  • m

    marcinmoskala

    04/29/2021, 5:42 AM
    When do you use fun interface instead of function type?
    d
    o
    • 3
    • 7
  • e

    Ellen Spertus

    05/04/2021, 5:27 PM
    For an article I'm writing, could you tell me which version of the following code you would write/recommend? Feel free to add options. 1️⃣
    if (b == true)
    2️⃣
    if (b == true)   // b could be null
    3️⃣
    if (b != null && b)
    1️⃣ 2
    2️⃣ 2
    l
    • 2
    • 1
  • c

    christophsturm

    05/05/2021, 2:29 PM
    is the official kotlin code style really no star imports?
    e
    • 2
    • 2
  • a

    arekolek

    05/10/2021, 7:20 PM
    1️⃣
    fun foo(bar: Bar) {
      if (!bar.canFoo) {
        <http://logger.info|logger.info>("No foo for this bar")
        return
      }
      // Make foo with bar
    }
    2️⃣
    fun foo(bar: Bar) {
      if (!bar.canFoo) {
        return <http://logger.info|logger.info>("No foo for this bar")
      }
      // Make foo with bar
    }
    2️⃣ 1
    1️⃣ 12
    l
    s
    • 3
    • 7
  • m

    Mark

    05/13/2021, 2:40 PM
    Is it standard practice to name a
    fun interface
    as a verb when the function is
    invoke
    ? Or maybe as a noun like here:
    fun interface ItemSelector {
        operator fun invoke(items: List<String>): String
    }
    
    val selectItem = object : ItemSelector { ... }
    val itemSelected = selectItem( ... )
    1. Verb 2. Noun
    p
    s
    • 3
    • 7
  • m

    marcinmoskala

    05/14/2021, 8:17 AM
    Based on the discussions here (1, 2), on Twitter, and my own experience, I tried to extract the general suggestions when to prefer function type and when functional interface. What do you think? Happy to see all kinds of suggestions and comments. (the article is not yet published, this is a preview) (tl;dr in the Summary) https://kt.academy/article/ek-function-types
    👍 1
    s
    • 2
    • 1
  • s

    Sam

    05/23/2021, 7:19 AM
    Hello Good morning Im curious about 2 solutions convert
    dp
    to
    px
    Solution 1:
    fun Int.dpToPx(context: Context): Int {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), context.resources.displayMetrics).toInt()
    }
    Solution 2:
    fun Int.dpToPx() = (Resources.getSystem().displayMetrics.density * this + 0.5f)
    so Which once is correct for multiple screen? Thanks.
    m
    • 2
    • 2
  • m

    Marc Knaup

    06/04/2021, 3:05 PM
    How do you name factory functions? 1️⃣ Simple function name
    fun interface SomeLongTypeNameFactory {
       fun create(): SomeLongTypeName
    }
    Con: Causes conflict if a class implements multiple factories. 2️⃣ Function name explicitly mentions type
    fun interface SomeLongTypeNameFactory {
       fun createSomeLongTypeName(): SomeLongTypeName
    }
    Con: Long & repetitive. 3️⃣ Other convention (add comment)
    3️⃣ 1
    2️⃣ 2
    1️⃣ 5
    m
    d
    • 3
    • 11
  • c

    Chris

    06/09/2021, 4:50 PM
    Which would you choose / use? 1️⃣
    it.toString()
    or 2️⃣
    "$it"
    or 3️⃣ something else? Is 1️⃣ and 2️⃣ equivalent?
    :yes: 2
    1️⃣ 10
    m
    m
    • 3
    • 7
  • v

    Victor Cardona

    06/10/2021, 11:54 AM
    I have a question after reading the coding conventions. It says to not separate extension methods from regular methods. So should I take that to mean that private extension methods should be within the class that makes use of them? I assume this would also apply to properties? For instance:
    class A {
        fun doSomething(): Unit {
            ...
        }
    
        private val B.things: List<Thing>
            get() = ...
    
        private fun C.helpMe(): Thing { ... }
    }
    I currently have the extensions at the top-level, but from reading the guidance it sounds like I should move them into the class itself.
    r
    • 2
    • 2
  • m

    miqbaldc

    06/17/2021, 10:59 PM
    which one do you prefer/recommend or maybe another alternative options to suggest? 1️⃣
    private fun AccountInfo?.isNotEmpty() = this != null && 
        id.isNullOrBlank().not() && 
        status.isNullOrBlank().not() &&
        something.isNullOrBlank().not()
    2️⃣
    private fun AccountInfo?.isNotEmpty() = this != null 
        && id.isNullOrBlank().not() 
        && status.isNullOrBlank().not()
        && something.isNullOrBlank().not()
    3️⃣ (linter will complain when exceeded the max length)
    private fun AccountInfo?.isNotEmpty() = this != null && id.isNullOrBlank().not() && status.isNullOrBlank().not() && something.isNullOrBlank().not()
    2️⃣ 4
    1️⃣ 1
    e
    • 2
    • 7
  • m

    miqbaldc

    06/18/2021, 6:28 AM
    any other alternative to suggest on below snippet code? 1️⃣
    fun doSomething(): String {
      return if 
        aMethodHere1()
      else
        aMethodHere2()
    }
    2️⃣
    fun doSomething(): String {
      return if aMethodHere1()
      else aMethodHere2()
    }
    3️⃣
    fun doSomething(): String {
      return if aMethodHere1() else aMethodHere2()
    }
    1️⃣ 1
    3️⃣ 1
    m
    t
    +2
    • 5
    • 6
  • m

    Mark

    06/22/2021, 3:35 AM
    Often I’m faced with a choice of declaring a private function in a companion object (good for encapsulation) or at the top file level (reduces indentation). Which do you prefer?
    class Foo {
        companion object {
            private fun bar1() { ... }
        }
    }
    
    private fun bar2() { ... }
    
    private fun Foo.Companion.bar3() { ... }
    1️⃣ companion object 2️⃣ top-level (file) 3️⃣ top-level companion extension
    2️⃣ 7
    4️⃣ 1
    a
    g
    • 3
    • 3
  • m

    miqbaldc

    07/12/2021, 8:09 AM
    // `cache` is an interface that has method `newToken()` & `unrecoverableSession()`
    Which one do you guys prefer, on the following snippet code? 1️⃣
    if (retryCount > RETRY_LIMIT) {
                 cache.unrecoverableSession()
                 return null
            }
    
            cache.newToken()?.let { newToken ->
                 return rewriteRequest(newToken)
            }
    
            return null
    or 2️⃣
    if (retryCount > RETRY_LIMIT) {
                cache.unrecoverableSession()
                return null
            }
    
            val newToken = cache.newToken()
    
            return if (newToken != null) {
                rewriteRequest(newToken)
            } else {
                cache.unrecoverableSession()
                null
            }
    or 3️⃣
    val newToken = cache.newToken()
    
            return when {
                retryCount > RETRY_LIMIT -> {
                   cache.unrecoverableSession()
                   null
                }
                newToken != null -> rewriteRequest(newToken)
                else -> {
                   cache.unrecoverableSession()
                   null
                }            
            }
    3️⃣ 3
    0️⃣ 1
    l
    t
    • 3
    • 3
  • k

    KV

    07/15/2021, 9:17 AM
    Hello, How to implement this below classes in better way? Class 1 has - DataResponse, Meta Response and List<IncludedResponse>
    @Serializable
    data class ApiResponse<T>(
        @SerialName("data") val data: DataResponse<T>,
        @SerialName("meta") val meta: MetaResponse?,
        @SerialName("included") val included: List<IncludedResponse>? = null
    )
    Class 2 has - List<DataResponse>, MetaResponse, List<IncludedResponse>
    @Serializable
    data class ListApiResponse<T>(
        @SerialName("data") val data: List<DataResponse<T>>,
        @SerialName("meta") val meta: MetaResponse?,
        @SerialName("included") val included: List<IncludedResponse>? = null
    )
    In both the class 
    List<IncludedResponse>?
     & 
    MetaResponse
      both are common only uncommon thing is 
    DataResponse
     & 
    List<DataResponse>
     .
    d
    t
    • 3
    • 4
  • m

    miqbaldc

    07/30/2021, 3:23 PM
    Context: There’s a migration process from
    UserV1
    to
    UserV2
    from our shared prefs Which one do you prefer? 1️⃣
    UserV1
    &
    UserV2
    is nullable if fetched from server, but we provide a blank/default value
    data class UserV1(status: String? = "", phoneNumber: String? = "", areaCode: Int? = -1)
    data class UserV2(
       accountInfo: Account? = null,
       domicileInfo: Domicile? = null, 
    )
    data class Account(status: String? = "", phoneNumber: String? = "")
    data class Domicile(areaCode: Int? = -1)
    
    fun UserV1?.toUserV2() = UserV2(
        accountInfo = Account(status = this?.status.orEmpty(), phoneNumber = this?.phoneNumber.orEmpty()),
        domicileInfo = Domicile(areaCode = this?.areaCode ?: -1)
    )
    fun UserV2?.orEmpty() = UserV2()
    // wrapping the whole if condition, e.g: (if a else b).orEmpty()
    fun findUser() = (if (userV2?.status?.isNullOrBlank() == false) userV2 else userV1.toUserV2()).orEmpty()
    2️⃣
    UserV1
    &
    UserV2
    is nullable if fetched from server, and leave it null (no blank/default value)
    data class UserV1(status: String? = null, phoneNumber: String? = null, areaCode: Int? = null)
    data class UserV2(
       accountInfo: Account? = null,
       domicileInfo: Domicile? = null, 
    )
    data class Account(status: String? = null, phoneNumber: String? = null)
    data class Domicile(areaCode: Int? = null)
    
    fun UserV1?.toUserV2() = UserV2(
        accountInfo = Account(status = this?.status.orEmpty(), phoneNumber = this?.phoneNumber.orEmpty()),
        domicileInfo = Domicile(areaCode = this?.areaCode ?: -1)
    )
    fun UserV2?.orEmpty() = UserV2()
    // call the `.orEmpty()` twice, e.g: if a.orEmpty() else b.orEmpty()
    fun findUser() = if (userV2?.status?.isNullOrBlank() == false) userV2.orEmpty() else userV1.toUserV2().orEmpty()
    2️⃣ 1
    t
    • 2
    • 1
  • d

    Dennis Titze

    08/12/2021, 11:51 AM
    Hi all, I'm building a linter to learn & experiment, and I'm wondering if there are style or other guidelines you feel are relevant but not enforced by linters because it's more on the semantic than syntactic level? I read through this channel quite a bit already, but now I am wondering if there are topics similar to tabs vs. spaces where you have strong (and maybe different) opinions.
    j
    • 2
    • 2
  • j

    James Whitehead

    08/12/2021, 1:56 PM
    Hi all, I have a question regarding the methods
    mutableSetOf()
    and
    linkedSetOf()
    . Given that both methods return a
    LinkedHashSet
    is there a recommendation on when to use one vs the other?
    d
    • 2
    • 1
Powered by Linen
Title
j

James Whitehead

08/12/2021, 1:56 PM
Hi all, I have a question regarding the methods
mutableSetOf()
and
linkedSetOf()
. Given that both methods return a
LinkedHashSet
is there a recommendation on when to use one vs the other?
d

diesieben07

08/12/2021, 2:09 PM
mutableSetOf
does not guarantee that you get a
LinkedHashSet
. All it guarantees is that you get a mutable set that preserves iteration order.
linkedHashSet
will always return a
LinkedHashSet
. So personally I'd always go for
mutableSetOf
unless you specifically need a
LinkedHashSet
.
➕ 2
👍 1
:thank-you: 1
View count: 3