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

    Vivek Modi

    06/10/2022, 10:48 AM
    Hey guys can we improve this piece of code?
    val filteredTopics by lazy { MutableStateFlow<List<Topics>>(emptyList()) }
    val temp = list.filter { it.topics != null }.filter { it.title == value.title }
    filteredTopics.value = temp.firstOrNull()?.topics?.sortedBy { topic -> topic.title } ?: emptyList()
    d
    e
    p
    • 4
    • 25
  • v

    Vivek Modi

    06/15/2022, 3:18 PM
    Hey guys, Can we improve this piece of code ?
    fun getConsultationCoverageList(): List<ContentWithTitle> {
        val list = mutableListOf<ContentWithTitle>()
        val consultation = getConsultationItem()
        consultation?.consultationCategories?.forEachIndexed { _, consultationCategory ->
            val paragraphs = mutableListOf<Paragraph>()
            consultationCategory.consultationTopics?.forEachIndexed { _, consultationTopics ->
                paragraphs.add(Paragraph(type = LIST_ITEM.type, text = consultationTopics.title))
            }
    
            list.add(ContentWithTitle(title = consultationCategory.title, content = Paragraphs(paragraphs), description = consultationCategory.description))
        }
        return list
    }
    j
    e
    • 3
    • 19
  • g

    George

    06/17/2022, 7:30 AM
    Hi guys, Which do u prefer and why? 1️⃣
    public interface Payload {
        public val data: Any
        public val error: Error
    }
    with factory fun:
    public fun <T : Any> Payload(data: T): Payload {
        return PayloadImpl(data)
    }
    public fun errorPayload(error: Error): Payload {
        return PayloadImpl(error = error)
    }
    2️⃣
    data class Payload(val data: Any, val error: Error)
    r
    j
    • 3
    • 18
  • n

    Nick Halase

    07/06/2022, 6:43 PM
    Is there a more elegant way to do this with the Kotlin standard lib?
    val values = listOf("name", "ASC", "description", "DESC")
    val propNames = values.filterIndexed { index, _ -> index.mod(2) == 0 }
    val sortDirections = values.filterIndexed { index, _ -> index.mod(2) != 0 }
    propNames zip sortDirections // [(name, ASC), (description, DESC)]
    e
    • 2
    • 2
  • n

    napperley

    07/31/2022, 11:36 PM
    Is there a Kotlinic (idiomatic Kotlin) way for multiple Coroutines to access/manipulate data? Below is some code relating to data access/manipulation:
    private val runningFunctions: FuncList = mutableListOf()
    typealias FuncList = MutableList<Pair<UInt, String>>
    
    internal fun addRunningFunction(pid: UInt, funcName: String) {
        runningFunctions += pid to funcName
    }
    
    internal fun removeRunningFunction(pid: UInt) {
        val list = runningFunctions.filter { it.first == pid }
        if (list.size == 1) runningFunctions -= list.first()
    }
    
    internal fun listRunningFunctions() = runningFunctions.toList()
    // ...
    Would the code above be scalable with multiple Coroutines running at the same time?
  • k

    Klitos Kyriacou

    08/03/2022, 3:45 PM
    Is there a way to use
    putAll
    on a mutable map, passing it another map and a value transformation function?
    putAll
    allows you to put all entries of another map into this map, but doesn't let you transform them on the fly.
    mapTo
    allows you to transform the entries but you can only write them to a Collection, not to a MutableMap. Is there a method that does what the commented-out line does?
    fun main() {
        val map1 = mapOf(1 to "one", 2 to "two", 3 to "three")
        val map2 = buildMap {
            put(4, "fourfour")
            put(5, "fivefive")
    
            // map1.mapTo(this) { (k, v) -> k to v + v } DOESN'T COMPILE
    
            // instead we have to use:
            putAll(map1.toMutableMap().apply { replaceAll { _, v -> v + v } })
            // or:
            putAll(map1.map { (k, v) -> k to v + v })
        }
        println(map2)
    }
    p
    • 2
    • 3
  • c

    christophsturm

    08/06/2022, 7:37 PM
    is there a way to get this to work?
    fun <Result> doit(lambda: () -> Result={Unit}) {
    
    }
    when the lambda is not passed i want Result to be of type Unit. I get the error Required: Result, found: Unit.
    e
    g
    • 3
    • 24
  • i

    iamthevoid

    08/09/2022, 6:46 AM
    What is the best way to replace multiple elements in list from another list? For example - some entities from list updates from server and should be replaced in cache by id In general in the case we have two lists of unknown size, let say N And loop gets us that calculation time will be O(n^2) - whether we should loop incoming list and then replace in stored with foreach or conversely Now i solve this like that , but something tell me that speed and performance could be better
    fun replaceAlerts(newAlerts: List<ExternalAlert>) {
            val data = stateFlow.value
            val existsAlerts = data.alerts.toMutableList()
            newAlerts.forEach { newAlert ->
                for (i in existsAlerts.indices) {
                    if (newAlert.id == existsAlerts[i].id) {
                        existsAlerts[i] = newAlert
                        return@forEach
                    }
                }
                existsAlerts.add(newAlert)
            }
            stateFlow.value = data.copy(alerts = existsAlerts)
        }
    j
    • 2
    • 5
  • j

    Jonathan Ellis

    08/09/2022, 3:12 PM
    is there a more idiomatic way to write a map-with-loop like this?
    val flowed = allShapes.map {
                var p = it
                for (i in 0 until STRETCH_ITERATIONS) {
                    p = flow(p)
                }
                p
            }
    e
    j
    • 3
    • 7
  • k

    Klitos Kyriacou

    08/16/2022, 1:20 PM
    Which one would you prefer: 1.
    rateLimiter.acquire()
    while (System.nanoTime() < endTime) {
        foo()
        bar()
        baz()
        if (System.nanoTime() < endTime)
           rateLimiter.acquire()
    }
    2.
    while (true) {
        rateLimiter.acquire()
        if (System.nanoTime() >= endTime)
            break
        foo()
        bar()
        baz()
    }
    3.
    while (run { rateLimiter.acquire(); System.nanoTime() < endTime }) {
        foo()
        bar()
        baz()
    }
    j
    e
    • 3
    • 9
  • t

    Travis Griggs

    08/16/2022, 6:28 PM
    Is there a better way to write the following:
    override fun compareTo(other: NamedObject): Int {
       // 5 cases
       // we both have null names, compare by oid
       // my name is null, his is not, i'm greater (1)
       // my name is not null, his is, im less (-1)
       // we both have names, compare them
       //    if names are equal, back to oid
       return when {
          name == null && other.name == null -> oid.compareTo(other.oid)
          name == null && other.name != null -> 1
          name != null && other.name == null -> -1
          else -> when (val nameCompare = name!!.compareTo(other.name!!)) {
             0 -> oid.compareTo(other.oid)
             else -> nameCompare
          }
       }
    }
    In particular, I was hoping to somehow avoid the !!'s in the middle. I was hoping to somehow invoke the smart pointer thing where it turns green and I don't have to check if it's null after I have previously.
    e
    • 2
    • 1
  • e

    Ellen Spertus

    08/20/2022, 5:58 PM
    I'm excited that I'll be teaching Intro CS with Kotlin this fall. Could someone review my use of KDoc in this code? I know my use of values is unidiomatic.
    /**
     * Prompts a user for their name and returns their response.
     */
    fun getUserName(): String {
        println("What is your name? ")
        val newName = readln()
        return newName
    }
    
    /**
     * Prints a greeting, using the person's [name].
     */
    fun greetUser(name: String) {
        println("Hello, $name")
    }
    
    /**
     * Carries on a brief conversation with a user.
     */
    fun converse() {
        val name = getUserName()
        greetUser(name)
    }
    t
    p
    • 3
    • 3
  • k

    KotlinLeaner

    09/06/2022, 8:20 PM
    Hi guys, I am getting difficult to understand this piece of code. I don't understand how
    let
    is going inside the lambda block if value is null. Can someone guide me on this. Thanks
    t
    • 2
    • 10
  • e

    Ellen Spertus

    09/18/2022, 1:25 AM
    I would like to be able to modify the properties in the initializer but nowhere else. Unfortunately, I don't think one can make private setters for properties declared as parameters. (Feel free to correct my terminology.)
    class USMoney(var dollars: Int, var cents: Int) {
        init {
            require(dollars >= 0 && cents >= 0)
            if (cents >= NUM_CENTS_PER_DOLLAR) {
                dollars += cents / NUM_CENTS_PER_DOLLAR
                cents %= NUM_CENTS_PER_DOLLAR        
            }
        }
    }
    I rewrote the code as shown. Is this a good approach and, if so, is there a standard naming convention for the parameters/properties?
    class USMoney(_dollars: Int, _cents: Int) {
        val dollars = _dollars + _cents / NUM_CENTS_PER_DOLLAR
        val cents = _cents % NUM_CENTS_PER_DOLLAR
        init {
            require(_dollars >= 0 && _cents >= 0)
        }
    }
    e
    k
    t
    • 4
    • 10
  • c

    christophsturm

    09/22/2022, 6:48 AM
    what is the most performant way to do this:
    log("going to work in items ${items.map {it.id}}")
    maybe a way to append directly to the string buffer instead of creating an array.
    t
    k
    • 3
    • 8
  • n

    nikolaymetchev

    09/23/2022, 10:48 AM
    Hello, can somebody explain why this doesn’t compile:
    class A {
        fun String.hello() {}
    }
    
    fun String.hello2() {
        A().hello() // cannot find hello()
    }
    w
    m
    k
    • 4
    • 7
  • e

    Ellen Spertus

    09/26/2022, 1:21 AM
    I'm trying to find a clean way to build a full name out of nullable components. I'm sure you can do better than I did:
    class Person (val personalName: String?, val middleInitial: String?, val familyName: String?) {
        override fun toString(): String {
            val nameParts = mutableListOf<String>()
            if (personalName != null) nameParts.add(personalName)
            if (middleInitial != null) nameParts.add(middleInitial)
            if (familyName != null) nameParts.add(familyName)
            return nameParts.joinToString(separator = " ")
        }
    }
    e
    • 2
    • 9
  • e

    Ellen Spertus

    09/29/2022, 2:19 PM
    Is there a better way of writing this without using scope functions, which I haven't introduced yet?
    l
    e
    k
    • 4
    • 11
  • ö

    Ömür Kartal - Timewax

    10/04/2022, 9:40 AM
    Hi all, I am trying to create a basic, generic validation implementation. Here is the test class showing 2 alternatives. (I could also create another method checking data types (Int, String, Double, etc) first and then calling validate method but I didn’t prefer to use it.) Could you please share your recommendations? Thanks..
  • c

    czuckie

    10/08/2022, 5:10 PM
    hi gang, is there any nice, easily understandable/identifiable way to turn a list of Byte (
    List<Byte>
    ) into a list of Shorts? (
    List<Short>
    ) such that [ 0x10, 0x01 ] would become [ 0x1001 ]
    b
    e
    • 3
    • 4
  • c

    christophsturm

    10/10/2022, 1:27 PM
    inline fun <reified C> name() = C::class.simpleName
    
    name<Collection<String>>()
    this returns “Collection”. is there a way make it return “Collection<String>“?
    j
    e
    • 3
    • 4
  • k

    Klitos Kyriacou

    10/10/2022, 6:04 PM
    A do-while loop seems more appropriate to me:
    var x: Int
            var y: Int
            do {
                x = Random.nextInt(0, NUM_COLS)
                y = Random.nextInt(0, NUM_ROWS)
            } while (isOccupied(x, y))
            place(entity, x, y)
    e
    e
    b
    • 4
    • 5
  • e

    Ellen Spertus

    10/11/2022, 1:35 AM
    I sometimes want to create getters of immutable versions of properties. Is there a better way than having two properties with different names?
    e
    • 2
    • 2
  • e

    Eduard Boloș

    10/13/2022, 10:49 AM
    Hello! Is
    this::field.isInitialized
    considered thread-safe? (
    field
    is a
    lateinit var
    ). Trying to figure out if I need to make sure the field gets created from the same thread that it's later accessed from, or if I can just rely on
    isInitialized
    being thread-safe 😄
    e
    c
    • 3
    • 3
  • h

    hisham bin awiad

    10/17/2022, 8:40 AM
    Can any one enhance this code 🌹
    private fun getCustomEmployeeShifts(
      employeeShifts: List<Shifts>?,
      approvedOvertimes: List<ApprovedOvertimesModel>?
    ): List<Shifts> {
    
      val resultList = mutableListOf<Shifts>()
      var sh: Shifts
    
      employeeShifts?.forEach { shiftsModel ->
        sh = shiftsModel
        approvedOvertimes?.forEach { appOverModel ->
          if (sh.id == appOverModel.employeeShiftId) {
            sh.approvedOvertimes.add(appOverModel)
          }
        }
        resultList.add(sh)
      }
    
      return resultList.toList()
    }
    j
    j
    r
    • 4
    • 10
  • p

    Paulo Cereda

    10/21/2022, 5:25 PM
    Hi friends! In this code, I ended up using
    var
    , but I was wondering if there was a way of getting rid of them (just as a personal challenge). Of course, my life would be easier if
    BreakIterator
    could implement
    Iterable
    , but no luck. 😉 Here's the code added for convenience:
    fun toGraphemes(str: String) = buildList {
        val boundary = BreakIterator.getCharacterInstance()
        boundary.setText(str)
        var start = boundary.first()
        var end = boundary.next()
        while (end != BreakIterator.DONE) {
            add(str.substring(start, end))
            start = end
            end = boundary.next()
        }
    }
    Any suggestion is welcome! Thank you! 🦆
    k
    e
    • 3
    • 5
  • a

    Andrew Simpson

    10/27/2022, 6:32 PM
    Hey guys, style-wise, do you think there is anything “wrong” with a secondary copy-constructor, like:
    class Person {
    
      constructor(id: Int, name: String)  
    
      constructor(person: Person) : this(person.id, person.name)
    
    }
    or would it be “more kotlin-like” to do something like a
    fun copy() = Person(id, name)
    method?
    z
    c
    • 3
    • 3
  • e

    Ellen Spertus

    11/01/2022, 8:46 PM
    I've implemented a Minecraft-like game for assignments in a class I am teaching. Classes include
    Mob
    (abstract),
    Zombie
    , and
    Spider
    . I would like to create a class
    Spawner<T: Mob>
    to create, for example, Spider Spawners (blocks that periodically construct and place new instances of
    Spider
    ). I'm trying to figure out the best way to instantiate a new instance of
    T
    from within
    Spawner<T>
    . I tried the following, but it doesn't work because of type erasure:
    class Spawner<T: Mob> {
        fun spawn() {
            val constructor = T::class.constructors.find { it.parameters.isEmpty() } // error: Cannot use 'T' as reified type parameter
            val newMob = constructor?.call()
        }
    }
    I'd rather not require the students to create factory classes. (This is an introductory programming class.) Instead I was thinking of faking a factory with a
    copy()
    method:
    class Spawner<T: Mob>(val mob: T) {
        fun spawn() {
            val newMob = mob.copy()
            // Place newMob on game board.
        }
    }
    
    abstract class Mob {
        abstract fun copy(): Mob
    }
    
    class Pigman: Mob() {
        override fun copy() = Pigman()
    }
    
    fun main() {
        val pigmanSpawner = Spawner<Pigman>(Pigman())
        pigmanSpawner.spawn()
    }
    Something I don't like about this is the type parameter isn't used and could be removed (if I changed the type of the
    mob
    property from
    T
    to
    Mob
    ).
    e
    m
    • 3
    • 7
  • g

    George

    11/09/2022, 5:54 PM
    In general should we prefer using simple try-catch pattern instead of
    runCatching
    in cases where we care about only one type of exception or is this too much neatpicking? For example:
    val result = runCatching { transaction() }
    return result.getOrElse {
        if (it is IllegalArgumentException) return null else throw it
    }
    vs
    return try {
        transaction()
    } catch (e: IllegalArgumentException) {
        null
    }
    Thanks in advance for any answers !
    p
    j
    e
    • 4
    • 12
  • m

    Marcello Galhardo

    11/16/2022, 12:22 AM
    What is an "associated object" in Kotlin, and what is its use cases? I found it by chance, and besides understand how the methods work - I'm not sure what is the use case for it. For reference: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/find-associated-object.html
    e
    • 2
    • 2
Powered by Linen
Title
m

Marcello Galhardo

11/16/2022, 12:22 AM
What is an "associated object" in Kotlin, and what is its use cases? I found it by chance, and besides understand how the methods work - I'm not sure what is the use case for it. For reference: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/find-associated-object.html
e

ephemient

11/16/2022, 12:36 AM
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect.full/companion-object.html and https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-class/object-instance.html are JVM-only; Kotlin/JS and Kotlin/Native don't have the same runtime reflection capabilities so they need this extra support
m

Marcello Galhardo

11/16/2022, 12:56 AM
Oh, very interesting. Thank you!
View count: 16