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

    voddan

    07/22/2017, 8:06 AM
    Should we request people who use :kotlin: in production to share their corporate code styles? I mean, many developers say they have their internal coding conventions, similar to what we are trying to do. We could learn some insights from them.
    y
    • 2
    • 2
  • g

    gabrielfv

    08/14/2017, 9:48 PM
    Idk if this is the right session, but what you guys think about nullable parameters defaulting to null?
    fun foo(bar: Int?)
    can be called like
    foo()
    , instead of having to write
    fun foo(bar: Int? = null)
    . I see people comonly reading the
    ?
    as sort of "opitional" in this context, and I don't see the point of calling
    foo(null)
    , though makes some sense when
    val a: Int? = mayReturnInt()
    foo(a)
    Is a common scenario
    g
    y
    • 3
    • 3
  • d

    david.bilik

    08/16/2017, 7:20 AM
    Hello. We have discussion with our colleagues about
    also
    vs
    apply
    usages. We have a method that needs to return some type but I would like to store instance of returned type to member property, something like
    lateinit var view : View
    fun createView(context : Context) : View {
      return with(context) {
        view = frameLayout {
        }
      }
    }
    this example would not compile because return type of view = frameLayout is unit. The variants to solve that are
    fun createView(context : Context) : View {
      return with(context) {
        view = frameLayout {
        }
        view
      }
    }
    fun createView(context : Context) : View {
      return with(context) {
        view = frameLayout {
        }.apply { view = this }
      }
    }
    fun createView(context : Context) : View {
      return with(context) {
        view = frameLayout {
        }.also { view = it }
      }
    }
    I prefer the
    also
    variant because it seems that this operator was made for this usages “do something also with this expression” and
    apply
    is for cases when i would like to modify instance in its context. Any opinions?
    m
    g
    +3
    • 6
    • 10
  • s

    Slackbot

    09/04/2017, 9:22 PM
    This message was deleted.
    k
    • 2
    • 1
  • l

    lovis

    09/05/2017, 8:23 AM
    please don’t
    👍 6
    k
    • 2
    • 3
  • b

    bj0

    09/09/2017, 2:21 AM
    #1 or
    list?.isNotEmpty() == true
    👍 8
  • k

    karelpeeters

    09/09/2017, 3:22 PM
    One of the common solution to
    null
    -related problems in Java is to return a "default value", and this works especially well with collections, there's rarely a reason for them to be null. Just make your mehods return empty collections instead.
    p
    c
    r
    • 4
    • 16
  • d

    Dmitry Kandalov

    09/15/2017, 10:08 AM
    Following up the conversation above about string concatenation formatting, I tried using
    +
    on new lines as @gabrielfv suggested:
    foo("one"
        + "two"
        + "three")
    only to find that it doesn’t work with
    return
    , e.g. the following doesn’t compile because of
    +
    on new line:
    fun bar(): String {
        return "one;"
            + "two;"
            + "three"
    }
    I’d argue this means that
    +
    and
    .plus()
    are already different enough to have different formatting 🙂 /cc @kevinmost
    k
    g
    • 3
    • 9
  • d

    dimsuz

    09/15/2017, 3:26 PM
    another thing is that it can be an rhs, and then the first variant get's kinda ugly
    t
    • 2
    • 1
  • v

    vlastachu

    09/20/2017, 4:33 PM
    Hi all. is it possible in android studio to align constructor assignment?
    CPTViewModel(
            selectionType = null,
            taskName = task.displayName,
            projectName = projectInfo.project.name,
            customerName = projectInfo.customer.name,
            isTaskVisible = true
    )
    to
    CPTViewModel(
            selectionType = null,
            taskName      = task.displayName,
            projectName   = projectInfo.project.name,
            customerName  = projectInfo.customer.name,
            isTaskVisible = true
    )
    :rage1: 1
    :no_red: 4
    y
    b
    • 3
    • 3
  • d

    dimsuz

    09/25/2017, 11:19 AM
    Maybe someone here will know what this suggestion is based on? Some specification/KEEP/etc? Where could I read more about this,
    y
    d
    • 3
    • 4
  • g

    gildor

    09/27/2017, 5:33 PM
    val url = it.imageUrl ?: return null
    val link = it.resizerlink ?: return null
    val width = it.imageWidth ?: return null
    val height = it.imageHeight ?: return null
    
    return Image(url, link, width.toInt(), height.toInt())
    3️⃣ 14
    :kotlin-flag: 3
    • 1
    • 2
  • g

    gabrielfv

    10/11/2017, 7:33 PM
    How would you guys recomend to use elvis operator on long expressions with line breaks?
    val a = foo.computeBar(Baz::class.java).fetchFirst() ?:
            return@thisComputationFun
    or
    val a = foo.computeBar(Baz::class.java).fetchFirst()
            ?: return@thisComputationFun
    or none at all? The IDE has recomended me to do this in place of the classic
    if (a == null) return@thisComputationFun
    d
    d
    b
    • 4
    • 10
  • m

    miha-x64

    10/12/2017, 4:31 PM
    Destricturing. Default indentation:
    val (
            distributor,
            items,
            shippingMethods,
            addresses,
            preferredAddressId
            ) = argument
    I propose:
    val (
            distributor,
            items,
            shippingMethods,
            addresses,
            preferredAddressId
    ) = argument
    y
    n
    • 3
    • 3
  • m

    michaelsims

    10/22/2017, 5:31 PM
    mainThreadScheduler.executeOnThread(Runnable {
        result.errorResult.let {
            if (it == null) {
                taskCallback.onSuccess(result.successResult)
            } else {
                taskCallback.onFailure(it)
            }
        }
    })
    a
    g
    m
    • 4
    • 15
  • y

    yole

    10/23/2017, 7:51 AM
    @joscha.alisch no. it’s perfectly fine to define extension functions for your own classes too, if the code is useful only in a limited context and is not worth cluttering the API with
    👍 1
    s
    • 2
    • 1
  • r

    raulraja

    10/24/2017, 11:58 PM
    1. If the first parameter is like in 2. Also last parameter closes with
    )
    is what I find more readable
    b
    • 2
    • 4
  • u

    uhe

    10/25/2017, 8:08 AM
    1️⃣ and 2️⃣ ... properties on a new line to avoid too much indentation but
    ) {
    on the same line as the last property because it's just a wasted line otherwise
    👎 1
    👍 2
    b
    t
    • 3
    • 11
  • r

    raulraja

    10/25/2017, 10:02 AM
    This brings up the question. What's the equivalent of something like scalafmt in Kotlin?
    y
    • 2
    • 3
  • m

    marcinmoskala

    10/25/2017, 3:33 PM
    @bdawg.io I am confused because I see 3 options and 2 numbers o.0 I would like to vote for 3️⃣
    b
    • 2
    • 2
  • b

    bamdmux

    10/26/2017, 5:27 AM
    From 1.1 you can declare them outside the sealed class but in the same file. I prefer it this way
    s
    • 2
    • 1
  • s

    Sean Corfield

    10/27/2017, 6:02 PM
    What about those folks who don't want to use IntelliJ? 😒imple_smile:
    b
    • 2
    • 1
  • z

    zredna

    11/06/2017, 2:14 PM
    What is the recommended way to declare private constants only used by a single class and why? 1. At the file level as private const val AWESOME_CONSTANT 2. Inside the class as private val awesomeConstant 3. In a companion object as private const val AWESOME_CONSTANT 4. Something else
    1️⃣ 4
    s
    • 2
    • 1
  • y

    yole

    11/14/2017, 1:34 PM
    no, there isn’t one and we have no plans to publish one
    😢 1
    b
    • 2
    • 1
  • l

    liminal

    11/19/2017, 2:18 PM
    is there a cleaner way to do this?
    fun isValid(): Boolean = noteText.isNotEmpty() && noteText.isNotBlank() && noteText.length > 3
    to avoid repeating noteText several times? thanks
    b
    k
    s
    • 4
    • 6
  • e

    enleur

    11/19/2017, 2:19 PM
    noteText.trim().length > 3
    👍 1
    t
    v
    • 3
    • 3
  • m

    marcinmoskala

    11/21/2017, 1:49 PM
    "Placing multiple declarations (classes, top-level functions or properties) in the same Kotlin source file is encouraged as long as these declarations are closely related to each other semantically." I totally agree for top level functions, properties and small objects. But people are often doing things like whole data model in single file and it is really hard to operate on that. It makes harder to find classes when files are not named with their names.
    m
    y
    • 3
    • 2
  • m

    marcinmoskala

    11/21/2017, 1:49 PM
    https://github.com/JetBrains/kotlin-web-site/blob/yole/styleguide/pages/docs/reference/coding-conventions.md#source-file-names I often hear that files with extension functions should be named with "Ext" suffix.
    y
    • 2
    • 3
  • m

    marcinmoskala

    11/21/2017, 1:52 PM
    https://github.com/JetBrains/kotlin-web-site/blob/yole/styleguide/pages/docs/reference/coding-conventions.md#naming-rules "use camel humps (org.example.myProject)." - If we follow Java convention (and I will strongly support that) then we should not use upper-case in package name https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html
    y
    • 2
    • 2
  • s

    Slackbot

    11/21/2017, 1:58 PM
    This message was deleted.
    y
    m
    a
    • 4
    • 13
Powered by Linen
Title
s

Slackbot

11/21/2017, 1:58 PM
This message was deleted.
y

yole

11/21/2017, 2:18 PM
this is an endless argument, and I’m not going to begin another round of it. suffice to say, Google’s Android style guide also has the same convention, and I’m not going to either contradict them or try to convince them to change their style guide
m

marcinmoskala

11/21/2017, 2:24 PM
This is why I would just avoid making any statements about it and I woild let developers do it how they want. Note that Kotlin/Native is opening Kotlin to lot's of new environments and platforms (Python, R etc) and they will not be happy if developers will be forced to change their naming habits.
y

yole

11/21/2017, 2:25 PM
following that logic we might as well give up on the style guide altogether. and the community has clearly stated that one is needed.
m

marcinmoskala

11/21/2017, 2:59 PM
It is not a point. Conventions are needed but not just for making conventions. They are needed when there is some purpose behind them. I feel that this rule is not improving anything. Stating that something is constant says nearly nothing - most properties in Kotlin are read-only.
Let's say I want to specify read only property with Gson. Do you want me to do it like that:
val gson = Gson()
or like that:
val GSON = Gson()
?
I would strongly prefer first option and I am pretty sure that this is how Gson was defined in KotlinConf-app
a

Andreas Sinz

11/21/2017, 3:06 PM
@marcinmoskala Gson() is not a constant
m

marcinmoskala

11/21/2017, 3:48 PM
@Andreas Sinz It is clear, but isn't it a top-level property holding data? I think that this is not clear
a

Andreas Sinz

11/21/2017, 10:07 PM
@marcinmoskala At the beginning it starts with
Names of constants
.
properties that hold data
probably can be confusing
m

marcinmoskala

11/22/2017, 6:15 AM
OK
y

yole

11/22/2017, 8:32 AM
the Android style guide contains a fairly elaborate definition of what is and isn’t a constant. we might just copy that
➕ 2
m

marcinmoskala

11/22/2017, 3:11 PM
After consideration I think that your argumentation is good and this is why I deleted my suggestion. Although some clarification might be useful.
y

yole

11/27/2017, 3:14 PM
I’ve clarified the text based on the wording in the Android style guide
👍 2
View count: 4