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
getting-started
  • l

    LastExceed

    11/16/2021, 12:46 PM

    https://i.imgur.com/rfsvzox.png▾

    does this mean 1.6 is now stable? website still says 1.5.31 and there is no announcement
    a
    j
    +2
    • 5
    • 8
  • m

    Manuel Dossinger

    11/16/2021, 2:00 PM
    if I have a List<T?> and want to filter elements such that I have a List<T> without null values and such that they satisfy a certain predicate, i could do
    myList.filterNotNull().filter { f(it) }
    , but that would essentially loop through the list twice, correct?
    j
    m
    +2
    • 5
    • 18
  • c

    Colton Idle

    11/17/2021, 2:02 AM
    I'm using firestore sdk for android which allows me to take a response and turn it into an object. My data class is defined as
    data class Person(
        val name: String = "",
    )
    but if firestore sends
    null
    , then even though the type is non-null, if I put a breakpoint... I can see that I do actually get a null value? Question: How can a non-null property like
    name
    be null? I'm assuming this is because of reflection/java-interop or something?
    s
    • 2
    • 2
  • m

    Michael Langford

    11/17/2021, 6:28 PM
    I Hi there. When porting an app from iOS, there are several lists of possible locations and methods of doing things in a medical context. Typically, we just want to use the enum's name (in the display and elsewhere, like json encoding), but occasionally, we'd like to slightly modify it. Example:
    enum class AdmininstrationReason {
      Prophy,
      StudyPlacebo,
      LightTherapy,
      DrinkingRelated, //<- We might want to display this as "Swallowing Disorders"
      Clotting,
      Other;
    }
    So I certainly can implement it as above and then use automatic parcelize/@Parcelable stuff and it works. I can even add an annotation and then get clever when displaying the value. This causes a performance hit by possibly dipping into reflection. I can make a companion object and use associatedBy to get part of the way there, but this breaks automated parcelization. I can make vals with getters for specific properties and use that, but it makes the per-item edits non-local to the list. I could make every item have a "String" value with it, but I don't want to have to add strings for some of these entries (of which there are hundreds) and duplicate the name of the items in an error prone matter.
    😒olved: 1
    👀 1
    j
    • 2
    • 9
  • a

    Alejandro Rios

    11/17/2021, 8:18 PM
    What is the channel for questions about Kover?
    m
    v
    • 3
    • 3
  • j

    jbnizet

    11/18/2021, 7:38 AM
    Let’s say you have
    data class Foo(val bar: String)
    . In IntelliJ , selecting
    Foo
    and hitting Alt-F7 only searches for the usages of the constructor. How do I make it search for all the usages of the class Foo?
    e
    j
    • 3
    • 5
  • m

    Mendess

    11/18/2021, 12:07 PM
    I'm having some problems with variance. I'm making my own result type:
    sealed class Result<out T> {
      class Success<out T>(val value: T): Result<T>()
      class Failure<out T>(val error: MyError): Result<T>()
    
      fun orDefault(d: T): T = when (this) {
        is Success<T> -> this.value
        is Failure<T> -> d
      }
    }
    I understand why it doesn't work, T is in
    in
    position when I marked it as
    out
    , what I want to know is: Is there some syntax to make
    T
    invariant or contravariant just for that method?
    j
    t
    • 3
    • 14
  • b

    Bart Whiteley

    11/18/2021, 4:50 PM
    I joined this group because some KMM docs said to come here and join a #kmm channel. Now I see the #kmm channel was archived. Is there a different Slack group for KMM discussions?
    m
    • 2
    • 2
  • b

    Bassam A.

    11/18/2021, 6:26 PM
    Hi. I’m planning to learn jetpack component. Who’s willing to team up?
    a
    s
    • 3
    • 6
  • a

    Ayfri

    11/19/2021, 4:33 PM
    Hi, I have a string (named
    selection
    ) that is equal to this pattern :
    [key=value, key=value, key=value]
    and I want to split it to a map containing all the keys and values, is there a simple way than this ?
    val attributes = selection.replace("[(\\w+)]".toRegex(), "$1").replace("\\s+".toRegex(), "").split(',').associate { it.substringBefore('=') to it.substringAfter('=') }
    j
    l
    • 3
    • 7
  • e

    Eric Boggs

    11/19/2021, 8:14 PM
    Hey all, I'm new to Kotlin and need some help understanding. I have a String that I need to break up in to chunks of 500 or so and pass to a suspending function of a library in the correct order. However, I'm having issues because .chunked isn't suspending. So, I attempted to use runBlocking, but I think that's causing threading problems because I can't seem to observe the result. Is there some established pattern to do this or am I completely off base here? Forgive my lack of knowledge. Any help or resources you can provide would be great. Here's an example of what I was thinking initially
    fun main() {
        // fake key
        val key: String = "N39w7DKQplfbMH6dD3WJQDG7SnR0QTznHTPn04F73TOxePLIZS924FGLszocSHV70HAlnrbSuKAkoQQpgTEDANTFPvQQxpUm7bHtW91zVBfFbJZYxP79vEPUGnOGOpWkix8GTwQpInSG8jSU3hxFbQXIewT7UvNX5ZvZXkLkmKtNqb6vjNiRCtk1fWQnCsCaCUIDHkNRigOjWKES15I81oF8qgS88vNuGix4SVPzGxW1GaUuGNWyRrQ2FXy5GAxITaVQgoTmu5OIjH5hWPIGpt0CdRIJFON770iX4Rqin6utcKZiainwC7rhuRsZw5zhO2uSA1di3ucGd2VeLgCcBnnJghZfCLioyUSPq4cImsmm3PWmo0CSAe7bJEKxvzTwoPsXRC8vuMSr9EpPRBudhvn0xGSB98MEC6ADao07cp8mIXJy9EDQofUddtutsAesg5jhSkN8N1yTg8CwcpXDFckgTZ2jV91iZjNhByY0pAaafg7d4esNLhbLTJCHV8Jq3Txen1rNOYkjfKlZfwolxprIYcKaPqYNkXnufutDGhEBaJFjXwO4en2G0RUMIBiWo2XhnjQjPs6YbLgQbwSmTewPzL8w4INbbGVxtLRdkNSnfOCT94WEBh3G2D5g26rdeFWhgEDehGIiyV0gpQuJahSpB29HJkV1SFcCA56nTNhpevffPJWyqvAMJMDChqnwE43MV04dhD1pbpE1UAix4lk5S3jEumwTZ8uDItgVuXGktqlRZkG2hMSYihHrpJyJCD6TwvYzHyydq505cY8Nhrexl4vZVgT24EikGvL6CDFBoCLJUgB2tg7maRoSbxOKHgSi3Sw9YSXo0JHBpfq3IePjTPjlW4a7TFD0w4pplFjr1IQBejxNcxfwMtjz2WTq2CbFkf9n5fvpXjMU8EFXCw0ODqsoNyWAJ02T7rNCBJM7p69fViXT2AVb5Y39bKPOXUBpZxeeOpaMX1nw93lUwbuXkMemwPlJYtcEqANb"
        key.chunked(500) {
            write(it)
        }
    }
    
    suspend fun write(key: CharSequence) {
        // Write the key in order
    }
    j
    • 2
    • 3
  • u

    ursus

    11/20/2021, 3:55 PM
    I'm trying to have typed Ids, so I created a interface
    interface Id : Comparable<Id> {
        val value: String
        
        override fun compareTo(other: Id): Int = value.compareTo(other.value)
        fun toString(): String = value
    }
    but it complains
    'toString' hides member of supertype 'Comparable' and needs 'override' modifier
    which is nonsense, but if I remove the comparable, then it complains that im hiding
    Any
    is this possible?
    a
    r
    p
    • 4
    • 8
  • j

    Jasin Colegrove

    11/21/2021, 3:28 PM
    I have a bunch of subclasses of ItemViewModels (tornadofx) that all have the same function that returns an entitysequence from a db. Is there a way to have a function that accepts a generic(my ItemViewModel subclasses) and call the appropriate subclass.getSequence() and return the entitysequence? It seems like this is possible but I'm having a hard time deciphering how
    j
    c
    • 3
    • 12
  • i

    ivan quintero

    11/21/2021, 5:29 PM
    I just built an MSI package for windows from a "hello world" app using #compose . After installing the app, I noticed it required over 100MB. Is this normal? I want to port an app I built in Electron JS because to save on disk requirements as well as RAM.
    c
    • 2
    • 3
  • a

    Ahmed

    11/22/2021, 10:36 AM
    Hey guys, I am using kotlin in my gradle.build file
    plugins {
        id("org.jetbrains.kotlin.jvm")
    }
    but for some reason, i am getting unresolved reference
    j
    • 2
    • 1
  • j

    Joshua Akinsola

    11/22/2021, 12:15 PM
    Hi all, does anyone know how to search through code on Android studio simply like you can on VS code?
    j
    m
    +2
    • 5
    • 17
  • p

    pavi2410

    11/22/2021, 1:52 PM
    I'm using
    URL.readText()
    extension function from stdlib but for some unknown reason, it's not
    close
    -ing the resources. However, the output is just printed fine at line 43
    j
    • 2
    • 8
  • i

    igor.wojda

    11/22/2021, 2:16 PM
    I wonder about coding conventions - the class layout:
    The contents of a class should go in the following order:
    
    Property declarations and initializer blocks
    
    Secondary constructors
    
    Method declarations
    
    Companion object
    What would be the reasoning of placing companion object at the end? (just personal style, or there is some actual argument behind it?)
    p
    m
    • 3
    • 4
  • m

    Marcin Wisniowski

    11/22/2021, 2:41 PM
    Is there a way to avoid object instantiation for a simple class like
    data class Point(val x: Int, val y: Int)
    ? In an API with lots of operations on such `Point`s, there is lots of
    Point
    objects being created. Changing the API to operate on x and y parameters separately without a
    Point
    class avoids the overhead, but makes the API less clean. Is there some language feature that can help here? I am looking for something like inline classes, but for two member properties.
    j
    m
    e
    • 4
    • 25
  • d

    Dipendra Singh

    11/22/2021, 3:46 PM
    Hi, I am trying to give a value to a entity (createEmail) based on entering enum type. Unfortunately, the value in the block is Unit type instead of CreateEmail. How to solve it? ( Method createErrorEmail is returning CreateEmail)
    val createEmail = {
                if (type == Type.ERROR) {
                    dataProvider.createErrorEmail(id)
                }
            }
    n
    r
    s
    • 4
    • 4
  • m

    Michael de Kaste

    11/23/2021, 11:06 AM
    Hello, I'm trying to implement a local Range type which includes the possibility to have nullable values; the idea is that a null end value means infinitely far away. Likewise I'd also love there to also be a null start value, but that's for later.
    interface OpenRange<T : Comparable<T>> {
        val start: T?
        val endInclusive: T?
        operator fun contains(value: T): Boolean = (
            start?.let { value >= it }
                ?: true
            ) && (endInclusive?.let { value <= it } ?: true)
        fun isEmpty(): Boolean = start != null && endInclusive != null && (start!! > endInclusive!!)
    }
    and then on something like
    operator fun LocalDateTime.rangeTo(other: LocalDateTime?) = object : OpenRange<LocalDateTime> {
        override val start: LocalDateTime = this@rangeTo
        override val endInclusive: LocalDateTime? = other
    }
    But ofcourse, LocalDateTime already has an rangeTo, but yet, this compiles without trouble. But when I call a localdatetime with the '..' operator now with a nullable other time, I get a type mismatch like the following.
    e
    k
    s
    • 4
    • 33
  • m

    martmists

    11/23/2021, 1:54 PM
    How would I pass "`--add-exports java.base/jdk.internal.misc=ALL-UNNAMED` " to compileKotlin in gradle? it's not a valid parameter but it still complains when compiling and using Unsafe
    e
    • 2
    • 13
  • s

    Stewart Stewart

    11/23/2021, 3:18 PM
    Is there a better way to search the standard library than the search bar here: https://kotlinlang.org/api/latest/jvm/stdlib/? That search bar is a fuzzy search of the full documentation site, and doc pages tend to dominate the results. I really just want to find classes and member functions.
    j
    • 2
    • 1
  • m

    Marcin Wisniowski

    11/23/2021, 11:35 PM
    Is a value class of a value class still working properly? Or will the inner value class end up boxed?
    s
    • 2
    • 4
  • r

    Rob Elliot

    11/24/2021, 11:44 AM
    Just realised that
    BufferedReader.forEachLine
    doesn’t distinguish between
    last line\nEOF
    and
    last lineEOF
    - in both cases the last line emitted is
    last line
    , whether it ends in a line feed or not. This is frustrating if you need to capture the output of the
    Reader
    exactly, but would also like to buffer based on line feeds rather than an arbitrary number of characters. Anyone know of a workaround? (It’s nearly NOT KOTLIN I know, because it just delegates to `java.io.BufferedReader.readLine`… hope the fact that kotlin has extension methods calling it justifies asking?!)
    e
    • 2
    • 8
  • i

    igor.wojda

    11/24/2021, 2:18 PM
    These Kotlin helper methods (lie
    mutableListOf
    ) to create collections are quite handy, but I find them a bit painfull for testing:
    class Bus {
    
        private val persons = mutableSetOf<Person>()
        
        fun addPerson(persons: Person) {
            persons.add(person)
        }
    }
    ^ no easy way to test that person was added to the list. We can always create a factory or pass in constructor, but I wonder how do you deal with that? Is there anything better?
    j
    r
    e
    • 4
    • 4
  • r

    ribesg

    11/25/2021, 8:58 AM
    How do you usually name your property in a
    value class
    ? I just always name it
    value
    and I wonder if there is another way that would make more sense
    j
    m
    +3
    • 6
    • 17
  • u

    ursus

    11/27/2021, 1:30 AM
    Whats the policy on extension functions on code I own? Say I have
    data class PhoneNumber(val normalized: String)
    and I need to format it with spaces etc before rendering in UI Is this a member or extension function?
    s
    d
    +2
    • 5
    • 9
  • m

    MrHash

    11/27/2021, 2:04 AM
    Hello This is Manish. I am looking to use Kotlin with multi-platform.
    m
    • 2
    • 2
  • v

    v79

    11/29/2021, 8:33 AM
    I'm looking for some best practice advice. I've got a simple class
    class Grid(val x:Int, val y: Int)
    but in some cases there won't be a value. Rather than make it nullable, I'd like to be able to return something like
    Grid.NONE
    instead. But not sure if this is a case for sealed classes, or interfaces, or an enum... I don't want to make
    Grid
    open, and it's likely that
    Grid
    will expand with additional properties and functions over time. Any suggestions?
    d
    t
    r
    • 4
    • 6
Powered by Linen
Title
v

v79

11/29/2021, 8:33 AM
I'm looking for some best practice advice. I've got a simple class
class Grid(val x:Int, val y: Int)
but in some cases there won't be a value. Rather than make it nullable, I'd like to be able to return something like
Grid.NONE
instead. But not sure if this is a case for sealed classes, or interfaces, or an enum... I don't want to make
Grid
open, and it's likely that
Grid
will expand with additional properties and functions over time. Any suggestions?
d

Dominaezzz

11/29/2021, 8:36 AM
Either nullable or sealed class.
t

Ties

11/29/2021, 8:36 AM
What bit won't have a value? as in, sometimes you can create a Grid, and sometimes you cannot?
v

v79

11/29/2021, 8:39 AM
If I were writing in Java, I'd definitely just have to add null checks. Maybe I'm overthinking it, it's a simple use case. For now I've gone sealed class, like this:
sealed interface TileGrid
class Grid(val x: Int, val y: Int) : TileGrid
object NONE : TileGrid
t

Ties

11/29/2021, 8:44 AM
There are a lot of good options, null is something different in kotlin than it is in java, since it is part of the kotlin type system. So returning null in java is a bit of an anti pattern, but in kotlin it is a good way to show the function can fail:
fun getGrid() : Grid?

getGrid()?.let{ println(it) }
is not a bad thing to do in kotlin. So it kinda depends on the rest of your application and how you use the function result
r

Rob Elliot

11/29/2021, 8:57 AM
You’d need a really strong reason not to use
null
to mean no value in Kotlin. Typesafe nulls transform them from a bad to a good idea. Arrow have even deprecated their
Option
class in favour of
null
. If for some reason
null
really doesn’t work, how about a
java.util.Optional
? Or use a typealias of
arrow.core.Either<Unit, T>
as suggested here: https://github.com/arrow-kt/arrow-core/issues/114#issuecomment-641211639 ?
👍 2
Particularly, the first class language support for
null
(null safe dereferencing with
?.
, null defaulting with
?:
, null aware types, including generic types) makes nullable values massively easier to work with than any other option. One thing to look out for is opportunities to use extension functions to simplify null handling: Given:
val x: Grid? = TODO()
fun Grid.doSomeTransform(): String = TODO()
val result: String? = x?.doSomeTransform()
is often nicer than
fun doSomeTransform(grid: Grid): String = TODO()
val result: String? = x?.run { doSomeTransform(this) }
View count: 5