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

    kristofdho

    02/23/2018, 12:11 PM
    your "flexible" solution voids all typesafety though
    c
    • 2
    • 1
  • r

    ralf

    03/06/2018, 2:39 AM
    I have this snippet
    .assertValueAt(2) {
                    it is ImageChangeEvent.ImageUpdated
                            && it.position == 0
                            && it.changedFields.contains(CollectImage.IMAGE_MODE)
                            && it.image.imageMode == newImageMode
                }
    The Kotlin Lint plugin complaints about this with
    Line must not begin with "&&"
    . Is this actually true? I couldn’t find anything in the coding conventions
    c
    • 2
    • 2
  • c

    cbruegg

    03/11/2018, 7:48 PM
    Since
    set(value) = ...
    for custom setters on variable is also allowed, I'd say it's no problem.
    Unit
    is just a normal return type and value in Kotlin.
    a
    c
    +2
    • 5
    • 7
  • a

    Andreas Sinz

    04/30/2018, 6:26 PM
    @travis Option 1 means
    catch exception
    ->
    put it in a Result
    ->
    rethrow another/the same exception
    , so definitely Option 2
    t
    • 2
    • 28
  • s

    Shawn

    06/06/2018, 1:53 PM
    private fun String.endpoint() = File(this).name.split("?")[0]
    vs
    private val String.endpoint
      get() = File(this).name.split("?")[0]
    a
    h
    l
    • 4
    • 9
  • l

    Luke

    07/19/2018, 5:37 PM
    Is the idiomatic way to call nullable lambdas
    lamdba?.invoke()
    ?
    f
    • 2
    • 2
  • g

    gildor

    07/27/2018, 1:07 PM
    Depends on case and constant name
    f
    • 2
    • 6
  • e

    elect

    08/06/2018, 1:40 PM
    is that limit fix or customizable?
    g
    • 2
    • 2
  • f

    fatih.yalmanbas

    08/16/2018, 8:25 AM
    Hello Guys, I have a question about code style. We are developing a UI test helper library for Android Instrumentation tests and thought having common assertions in separate files can be convenient. But we are not sure if we should declare those functions top-level or in an object such as “ImageViewAssertions”. *So my question is: * When do you use top-level (root package) functions and when do you put them inside objects ?
    c
    d
    • 3
    • 7
  • б

    Бежан Александр

    08/28/2018, 10:47 AM
    Hi guys. I want to limit amount of Kotlin features and code style, so it doesn’t compile or at least shows warnings for incorrect style. Is it possible ?
    c
    c
    g
    • 4
    • 6
  • e

    enleur

    10/08/2018, 2:42 PM
    what is the preferred style to write multiline condition expressions? 1:
    val c = if (a !== b)
        "1" else
        "2"
    2:
    val c = if (a !== b)
        "1"
    else
        "2"
    3:
    val c = if (a !== b) "1"
    else "2"
    4:
    val c = if (a !== b) {
        "1"
    } else {
        "2"
    }
    4️⃣ 20
    1️⃣ 1
    3️⃣ 1
    2️⃣ 2
    h
    g
    • 3
    • 2
  • s

    Shawn

    10/08/2018, 2:46 PM
    if the if and else are both single-line expressions I’m kinda partial to this
    val result = if (condition) first
                 else second
    b
    • 2
    • 2
  • e

    enleur

    10/08/2018, 2:49 PM
    could not find any information in https://kotlinlang.org/docs/reference/coding-conventions.html
    a
    • 2
    • 2
  • s

    Shawn

    10/23/2018, 3:40 PM
    !
    is a single, slender character that’s easier to gloss over than
    not
    is
    g
    • 2
    • 2
  • h

    Hullaballoonatic

    10/23/2018, 4:27 PM
    yeah, i also think that it preceding the rest of the call bothers me, but what are you gonna do with unary operators?
    h
    • 2
    • 1
  • y

    yole

    11/02/2018, 8:36 AM
    the feature disparity between the two formatters is quite intentional. the focus for the Kotlin formatter is to support the official Kotlin style guide. we do not want to encourage people to bring all of their accumulated code formatting idiosyncrasies to Kotlin
    👍 4
    💯 2
    m
    • 2
    • 1
  • y

    yole

    11/02/2018, 8:38 AM
    and the reason why we aren’t going to endorse “align fields in columns” in the official style guide is exactly what @egorand says: one of the guiding principles of the official style guide is to avoid whitespace changes induced by changing the length of identifiers as much as possible
    👍 3
    h
    • 2
    • 1
  • h

    Hullaballoonatic

    11/14/2018, 8:19 PM
    It's so hard for me to avoid the temptation to just include all functionality corresponding to an object within that object itself
    i
    • 2
    • 1
  • l

    liminal

    11/18/2018, 8:49 PM
    If I have an
    enum
    class, is it better to declare it inside a data class (where it logically belongs) or top-level outside of the class declaration?
    e
    • 2
    • 3
  • e

    enleur

    11/19/2018, 6:15 PM
    https://ktor.io/quickstart/code-style.html#with-star-imports who uses this in projects?
    ➕ 1
    e
    g
    • 3
    • 9
  • h

    hudsonb

    11/20/2018, 2:22 AM
    @elizarov any good articles discussing “Kotlin-style design and prefer extensions over members”?
    c
    w
    • 3
    • 7
  • a

    arekolek

    11/22/2018, 9:26 AM
    Do you always put all the property declarations in a class before any method declaration, or do you make exceptions (like a property used in just one method further down)?
    s
    h
    • 3
    • 2
  • k

    kenkyee

    11/27/2018, 2:16 PM
    For constructor param indentation when each is on a separate line, is it supposed to be 4 or 8? Android studio defaults to 8 but ktlint flags it as 4...
    m
    b
    • 3
    • 5
  • a

    arekolek

    11/27/2018, 2:34 PM
    there’s no consensus even between the two style guides that I know of • https://kotlinlang.org/docs/reference/coding-conventions.html#class-header-formatting • https://developer.android.com/kotlin/style-guide#continuation_indent I prefer the Kotlin one personally 😄
    m
    b
    • 3
    • 4
  • k

    kenkyee

    11/27/2018, 3:02 PM
    convinced everyone to use the 4...weird that Android Studio's default isn't 4. The examples in the guides seem to prefer 4: fun <T> Iterable<T>.joinToString( separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "" ): String { (though that's method call parameters vs. constructor params which the Android style guide doesn't cover) and from the Kotlin style guide class Person( id: Int, name: String, surname: String ) : Human(id, name) { ... }
    s
    • 2
    • 1
  • t

    turansky

    12/03/2018, 10:37 AM
    Is there any recomendation for enum usage?
    -.kt
    2️⃣ 1
    g
    • 2
    • 1
  • t

    tarek

    12/12/2018, 10:09 PM
    Hi Is it possible to compose extension functions ? Let's say I have an extension function :
    val myFunc: A.() -> Unit = { // this: A
        customField = "value" 
    }
    val otherFunc: A.() -> Unit = { // this: A
        otherField = "other"
    }
    I want to have a function that is the combination of both above I don't know how to write this.
    s
    g
    • 3
    • 2
  • g

    ghedeon

    12/18/2018, 5:15 PM
    Don't you find yourself in a situation, when you start writing
    with
    then realize that the type is nullable and fallback to
    ?.apply{}
    ? Relevant question on SO: https://stackoverflow.com/questions/35723226/how-to-use-kotlins-with-expression-for-nullable-types
    g
    • 2
    • 4
  • j

    james.cruz

    12/19/2018, 6:28 AM
    Hello, I have a public interface called "Foo" and it has an internal default
    object
    implementation. What's the preferred way to get the implementation's instance? 1️⃣ Companion object as the default implementation
    interface Foo {
      companion object : Foo {
        // default implementation goes here
    2️⃣ Quasi constructor
    interface Foo {
      companion object {
        operator fun invoke(): Foo = DefaultFooImpl
    3️⃣ Top level method
    fun defaultFoo(): Foo = DefaultFooImpl
    c
    m
    b
    • 4
    • 7
  • e

    egorand

    12/21/2018, 3:19 PM
    Oh interesting. How would you translate the snippet above into free-form?
    c
    • 2
    • 5
Powered by Linen
Title
e

egorand

12/21/2018, 3:19 PM
Oh interesting. How would you translate the snippet above into free-form?
c

Czar

12/21/2018, 4:53 PM
That snippet being a completely synthetic example won't make a good primer, I think. Instead look at stdlib docs for better examples. Just to save you some keystrokes and clicks, here's a link to a file with a lot of docs (randomly selected by me) https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/common/src/kotlin/MathH.kt
e

egorand

12/21/2018, 4:55 PM
Real-world example - generating Kotlin classes for proto messages, where each field in the message is translated into a property and has docs
the file you’ve linked contains top-level functions only, which is a different use case
c

Czar

12/21/2018, 5:06 PM
Well, the class I shared is a real world example 🙂 As for the specific case you mentioned, I don't think there is any common convention. I tend to agree with your stated opinion about ordering by appearance in code. If Android style guide is an issue, you can reorder the code so that all params come before properties, then your doc would conform both to Android convention and the common sense ordering 🙂
e

egorand

12/21/2018, 5:33 PM
haha, yes, I like it 🙂
View count: 3