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

    marcinmoskala

    11/21/2017, 2:00 PM
    https://github.com/JetBrains/kotlin-web-site/blob/yole/styleguide/pages/docs/reference/coding-conventions.md#choosing-good-names Good addition is that form of the method can suggest if method is mutating the object or returning new. For instance
    sort
    is sorting collection while
    sorted
    is returning sorted copy of the collection.
    y
    • 2
    • 1
  • m

    marcinmoskala

    11/21/2017, 2:01 PM
    https://github.com/JetBrains/kotlin-web-site/blob/yole/styleguide/pages/docs/reference/coding-conventions.md#names-for-backing-properties I would suggest to avoid backing properties.
    y
    • 2
    • 1
  • m

    marcinmoskala

    11/21/2017, 2:04 PM
    https://github.com/JetBrains/kotlin-web-site/blob/yole/styleguide/pages/docs/reference/coding-conventions.md#horizontal-whitespace This might sound stupid but developers are often doing it: I would suggest to start comment from upper case. I would also suggest to finish with dot if comment contains more then single sentence.
    y
    • 2
    • 2
  • m

    marcinmoskala

    11/21/2017, 2:06 PM
    "Use regular indent (4 spaces) for constructor parameters." I strongly agree with that, but autocorrection is still changing it to 8 spaces indent!
    y
    • 2
    • 2
  • m

    marcinmoskala

    11/21/2017, 2:18 PM
    "Do not sort the method declarations alphabetically or by visibility, and do not separate regular methods from extension methods." I was thought to sort methods by visibility and I think that it is really important because public functions are forming class interface! If someone is reading the class then he is first reading this functions. override functions should be placed before because they are even more important - they specify characteristic class behavior. I am from Android world and over there nearly all guidelines are stating that Activity/Fragment lifecycle should be placed before other public methods. protected functions are also specifying some kind of an interface - inheritance interface. This is why they all should be separated. Also all this functions should be as short as possiblie and ant their logic should be moved to private functions with behavior-explanatory names. This way someone that is reading the class clearly see that is happening and how he can use class, and he can understand it without reading implementation details that are placed in the private functions. About keeping close methods that are working together: I agree, but it is not as important as general class readability because is developer want to read specific function then he can quickly jump to it using Ctrl or using Ctrl+F on Github.
    y
    • 2
    • 2
  • m

    marcinmoskala

    11/21/2017, 2:21 PM
    https://github.com/JetBrains/kotlin-web-site/blob/yole/styleguide/pages/docs/reference/coding-conventions.md#overload-layout "Always put overloads next to each other in a class." Don't you think that it is not coherent with statement "Do not sort the method declarations alphabetically or by visibility, and do not separate regular methods from extension methods. Instead, put related stuff together, so that someone reading the class from top to bottom would be able to follow the logic of what's happening. "?
    y
    • 2
    • 1
  • m

    marcinmoskala

    11/21/2017, 2:31 PM
    This is why I am always doing like that:
    fun bestStudents(allStudents: List<Student>) = allStudents
            .sortedBy { it.grade }
            .take(10)
    y
    • 2
    • 2
  • m

    marcinmoskala

    11/21/2017, 2:34 PM
    fun bigger(a: Int, b: Int) = if (a > b)
        a
    else
        b
    
    fun greet(a: Any) = when (a) {
        is String -> "Hello String"
        is Number -> "Hello Number"
        else -> "I don't know you! Go away!"
    }
    y
    • 2
    • 3
  • m

    marcinmoskala

    11/21/2017, 2:40 PM
    https://github.com/JetBrains/kotlin-web-site/blob/yole/styleguide/pages/docs/reference/coding-conventions.md#chained-call-wrapping 1. I think that you forgot to use safe call in the example 2. You cannot separate ? and . in safe call co it is actually the same rule as that dot should be placed in the next line with method call
    y
    • 2
    • 1
  • m

    marcinmoskala

    11/21/2017, 2:46 PM
    https://github.com/JetBrains/kotlin-web-site/blob/yole/styleguide/pages/docs/reference/coding-conventions.md#modifiers I hope it will be supported by autostyling because it is impossible to remember xP
    y
    • 2
    • 1
  • m

    marcinmoskala

    11/21/2017, 2:48 PM
    https://github.com/JetBrains/kotlin-web-site/blob/yole/styleguide/pages/docs/reference/coding-conventions.md#platform-types What is wrong with unsafe casting there if we know that type cannot be null?
    y
    • 2
    • 3
  • m

    marcinmoskala

    11/21/2017, 2:51 PM
    https://github.com/JetBrains/kotlin-web-site/blob/yole/styleguide/pages/docs/reference/coding-conventions.md#platform-types I would suggest to use
    trimMargin
    to not trim intentional indent:
    val a = """if(a > 1) {
              |    return a
              |}""".trimMargin()
    y
    • 2
    • 1
  • o

    oblakr24

    12/18/2017, 9:12 AM
    Quick question: enum classes naming: capitalized (Swift-style) or all-caps (Java-style)? I don't see it stated explicitly in https://kotlinlang.org/docs/reference/enum-classes.html, and I prefer capitalized (because the editor already does a good-enough color-markup to distinguish it, and all-caps looks ugly)
    s
    h
    • 3
    • 7
  • d

    diesieben07

    12/18/2017, 9:41 AM
    There is still no official answer on how domain names with hyphens should be converted to package names. The "Java-way" of using underscores now triggers a code-style warning. 😞
    g
    s
    +2
    • 5
    • 16
  • p

    pardom

    12/20/2017, 5:21 PM
    👏 👏 👏 @yole will the IntelliJ formatter be updated, too?
    👍 1
    ➕ 1
    y
    • 2
    • 1
  • n

    nic

    01/09/2018, 11:22 PM
    This may be the wrong channel for this, but what would be the best way to set up a multiple property that can be set as null, but never retrieved as null. Essentially a mutable
    lazy
    property that can be cleared, and the next time you go to grab it, it creates a new instance of itself, so you don’t have to scatter the code with
    variable?.
    everywhere, since you’ll never grab a null version of it
    l
    k
    • 3
    • 21
  • t

    tapchicoma

    01/12/2018, 7:01 AM
    Would you go with 1️⃣ :
    nullableValue = NullableValue(1, 2, 3)
    nullableValue?.someProperty = 4
    or 2️⃣ :
    nullableValue = NullableValue(1, 2, 3).apply {
        someProperty = 4
    }
    where
    NullableValue
    constructor has a lot of params.
    2️⃣ 17
    d
    b
    • 3
    • 5
  • v

    voddan

    01/12/2018, 10:51 PM
    Is
    NullableValue(.....)
    a function or a constructor?
    ➕ 1
    r
    • 2
    • 1
  • r

    robin

    01/13/2018, 5:47 PM
    So the coding conventions suggest to put all files in the root package directly in the root folder of the application. I want to follow this, but IntelliJ makes it a bit cumbersome, because it doesn't seem to recognize that rule. When I create a new file for the package
    my.root.package.subpackage
    , the new file will get
    package subpackage
    at the start, because of course the IDE doesn't know about my root package. Right now I got it to work by adding the root package manually inside the new file template in the settings, but that seems way too hacky for me. Is there a better approach to get the desired behavior?
    y
    • 2
    • 2
  • d

    Dave Leeds

    01/15/2018, 8:40 PM
    Here’s the recommended class layout from the coding conventions document:
    - Property declarations and initializer blocks
    - Secondary constructors
    - Method declarations
    - Companion object
    
    Do not sort the method declarations alphabetically or by visibility, and do not separate regular methods from extension methods. Instead, put related stuff together, so that someone reading the class from top to bottom would be able to follow the logic of what's happening.
    I’m looking for thoughts on location of private extension properties. Would you tend to put them: 1️⃣ With the regular properties of the class 2️⃣ Near the functions that use them 3️⃣ Somewhere else (please specify)
    2️⃣ 12
    • 1
    • 1
  • a

    arekolek

    01/17/2018, 2:58 PM
    I’m trying to find the bit of kotlin documentation that said replacing functions with val properties is fine as long as they return the same result over subsequent, invocations, work in constant time, etc. Anyone know where that was mentioned?
    a
    • 2
    • 3
  • u

    uhe

    01/18/2018, 9:54 AM
    val foo = mapOf<String, String>()[""] ?: longAssMethodNameWithLongAssParameters(lookAtMeImSoLong = "so very long!") inlineInfixFun { return }
    becomes
    val foo = mapOf<String, String>()[""]
                ?: longAssMethodNameWithLongAssParameters(lookAtMeImSoLong = "so very long!")
                inlineInfixFun { return }
    which doesn't compile any longer
    :youtrack: 2
    k
    • 2
    • 2
  • c

    Czar

    01/18/2018, 1:01 PM
    Oooh, forgot about this channel. I have a question about class layout.
    companion object
    is suggested to be placed at the bottom of the class. This does not make sense to me. CO usually contains constants or stuff like
    : KLogging()
    so why would anyone want to hide it at the bottom? These constants and
    logger
    property in case of
    KLogging
    IMO should be declared at the top so that they be easy to reference "at a glance".
    k
    h
    • 3
    • 5
  • e

    enleur

    01/23/2018, 3:13 PM
    “now” looks better for me
    w
    c
    • 3
    • 17
  • e

    efemoney

    01/25/2018, 7:03 AM
    I love type hints but they dont look so great with DSL things EDIT: They dont look great in that particular case
    y
    • 2
    • 2
  • e

    efemoney

    01/25/2018, 7:34 AM
    Yeah thanks for confirming @gildor
    g
    • 2
    • 2
  • h

    helpermethod

    01/25/2018, 9:39 AM
    @efemoney Hi, what it the name of that JSON Builder DSL?
    e
    • 2
    • 3
  • m

    menegatti

    01/26/2018, 2:31 PM
    lateinit
    cannot be applied to primitive types such as Strings and Integers
    r
    • 2
    • 4
  • m

    menegatti

    02/22/2018, 2:48 PM
    there are coding conventions here https://kotlinlang.org/docs/reference/coding-conventions.html
    s
    g
    • 3
    • 4
  • w

    waqas

    02/23/2018, 11:43 AM
    What'e the idiomatic way checking null on multiple variables and passing those to a function which takes not nulls? I went through this -> https://discuss.kotlinlang.org/t/kotlin-null-check-for-multiple-nullable-vars/1946/8 I liked this approach but is there something better?
    inline fun <A, B, R> ifNotNull(a: A?, b: B?, code: (A, B) -> R) {
        if (a != null && b != null) {
            code(a, b)
        }
    }
    ...
        fun test() {
            ifNotNull(name, age) { name, age ->
                doSth(name, age)
            }
        }
    b
    • 2
    • 1
Powered by Linen
Title
w

waqas

02/23/2018, 11:43 AM
What'e the idiomatic way checking null on multiple variables and passing those to a function which takes not nulls? I went through this -> https://discuss.kotlinlang.org/t/kotlin-null-check-for-multiple-nullable-vars/1946/8 I liked this approach but is there something better?
inline fun <A, B, R> ifNotNull(a: A?, b: B?, code: (A, B) -> R) {
    if (a != null && b != null) {
        code(a, b)
    }
}
...
    fun test() {
        ifNotNull(name, age) { name, age ->
            doSth(name, age)
        }
    }
b

bdawg.io

08/08/2018, 6:38 PM
I’m really not sure why my Slack is still back in February lol. But you could also do
fun test() {
    ignoreNpe {
        doSth(requireNotNull(name), requireNotNull(age))
    }
}
View count: 3