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

    miqbaldc

    11/18/2021, 8:43 AM
    Any alternative suggestion (more kotlin idiom/functional approach) to extract the following string? from:
    <deeplink scheme>://jobs?category_id=asdf&employment_type=FULLTIME
    into a query parameter (what I can think of atm was map):
    mapOf(
       "category_id" to "asdf",
       "employment_type" to "FULLTIME"
    )
    my code attempts in 🧵
    s
    • 2
    • 3
  • l

    LeoColman

    11/24/2021, 1:07 AM
    Hey guys!
    var millis = 123L
    var i = 0
    buildList<Pair<TimeUnit, Long>> {
      add(Year to (millis / MillisInYear))
      millis -= (get(i++).second * MillisInYear)
      add(Month to (millis / MillisInMonth))
      millis -= (get(i++).second * MillisInMonth)
      add(Day to (millis / MillisInDay))
      millis -= (get(i++).second * MillisInDay)
      add(Hour to (millis / MillisInHour))
      millis -= (get(i++).second * MillisInHour)
      add(Minute to (millis / MillisInMinute))
      millis -= (get(i++).second * MillisInMinute)
      add(Second to (millis / 1_000))
      millis -= (get(i++).second * 1_000)
      add(Millisecond to millis)
    }
    This code is used to make a timer/counter (picture) However, it's very ugly as it is. How can I enhance this?
    j
    b
    +3
    • 6
    • 8
  • s

    Sergio C.

    11/30/2021, 6:23 PM
    Is there a way to simplify this logic?
    var qtdTotal = 0.0f
                val partition = response?.partition { it.uidCaracteristica != 0 }
                val uidGroup = partition?.first?.groupBy { it.produto }?.toMutableMap() ?: mutableMapOf()
                uidGroup[0] = partition?.second ?: listOf()
                uidGroup.forEach { (key, uidsList) ->
                    if (key == 0) {
                        uidsList.forEach { stk ->
                            addRow(
                                stk.description ?: "", "", "", "",
                                extraInfo = listOf(
                                    stk.produto.toString(),
                                    stk.description ?: "",
                                    stk.codbarras ?: "",
                                    stk.referencia ?: ""
                                )
                            )
                            qtdTotal += stk.stock ?: 0.0f
                        }
                    } else {
                        val caracteristicas = uidsList.map {
                                ReportsDataset.Row(
                                    it.caracteristica ?: "",
                                    it.stkmin?.toString() ?: "",
                                    it.stkmax?.toString() ?: "",
                                    it.stock?.toString() ?: "",
                                    extraInfo = listOf(it.uidCaracteristica?.toString() ?: "")
                                )
                            }
                        val stk = uidsList.first()
                        addRow(
                            stk.description ?: "", "", "", "",
                            extraRows = caracteristicas,
                            extraInfo = listOf(
                                stk.produto.toString(),
                                stk.description ?: "",
                                stk.codbarras ?: "",
                                stk.referencia ?: ""
                            )
                        )
                        qtdTotal += stk.stock ?: 0.0f
                    }
                }
    r
    j
    • 3
    • 5
  • m

    miqbaldc

    12/13/2021, 12:07 PM
    Does the UseCase always necessary to have a
    CoroutineDispatcher
    and returns
    Flow<T>
    or
    suspend
    (return
    T
    ) is enough?
    abstract class FlowUseCase<out T, in Params> constructor(
        private val threadExecutor: CoroutineDispatcher
    ) {
        protected abstract fun execute(params: Params? = null): Flow<T>
        open operator fun invoke(params: Params? = null): Flow<T> =
            execute(params).flowOn(threadExecutor)
    }
    What implementation did you folks use, would love to know the pros n cons
    m
    s
    • 3
    • 3
  • s

    Slackbot

    01/06/2022, 10:08 PM
    This message was deleted.
    m
    v
    • 3
    • 4
  • c

    chansek

    01/28/2022, 6:19 AM
    How can I evaluate both of these in a single operator chain?
    val adminOf = user.roles
        .filter { it.isAdmin() }
        .map { it.entityId to it.entity }
        .toMap()
    val serviceProviderOf = user.roles
        .filter { it.isServiceProvider() }
        .map { it.entityId to it.entity }
        .toMap()
    j
    m
    e
    • 4
    • 4
  • m

    myanmarking

    01/28/2022, 7:45 PM
    Can any1 help me understand why the built-in type inference for map is not working
    j
    j
    • 3
    • 7
  • h

    hho

    02/02/2022, 11:16 AM
    I'm torn … do you extract the
    return
    even if some branches don't return anything? I think I might like the version with multiple return statements better in this case…
    return if (someExpr) {
      doSomeStuff()
      someThing
    } else if (otherExpr) {
      doOtherStuff()
      otherThing
    } else {
      throw RuntimeException("uh oh")
    }
    j
    j
    • 3
    • 7
  • m

    miqbaldc

    02/03/2022, 1:55 PM
    Any recommendation or preferences for following snippet?
    preconditions
    or
    throw
    for this case, maybe any references?
    1️⃣
    suspend fun updatePushToken(newPushToken: String): Result<String> = invoke {
        require(newPushToken.isNotEmpty()) { "Push token is required to not empty" }
    
        kotlin.runCatching { repository.agentUpdatePushToken(newPushToken = newPushToken) }
    }
    or 2️⃣
    suspend fun updatePushToken(newPushToken: String): Result<String> = invoke {
            
            if (newPushToken.isEmpty()) {
                throw IllegalArgumentException("Push token is required to not empty")
            }
            
            kotlin.runCatching { repository.agentUpdatePushToken(newPushToken = newPushToken) }
        }
    1️⃣ 2
    j
    e
    m
    • 4
    • 14
  • j

    jwass

    02/03/2022, 2:03 PM
    I’ve got a
    data class Thing(val x: Int, val y: Int, val ignoreMe: String)
    which I want to put in a set to perform set operations, but ignore certain fields for the purpose of set comparison. i.e. only considering a subset of fields for equality comparisons.
    val x = setOf(Thing(5, 5, "Hello"), Thing(10, 6, "Goodbye"), Thing(100, 3, "Zzzz"))
    val y = setOf(Thing(5, 5, "Baz"), Thing(10, 6, "Goodbye"))
    val result = x.minus(y)
     -> result = setOf(Thing(100, 3, "Zzzz")) // because Thing(5, 5, "Hello") is considered equal to Thing(5, 5, "Baz")
    In reality the data classes are a bit richer, about 6 fields. I thought I could build a sorted set with a custom comparator, but that requires implementing a sorting on the data classes when I only really want a custom equality for that set. I only want this custom equality behaviour in one context, so it’s not appropriate to actually re-implement
    equals
    etc on the data classes directly. Any ideas about if there’s a simple way to achieve this? (edit - found a nice idea on stack overflow - just wrap the objects in a special purpose class)
    j
    • 2
    • 20
  • t

    therealbluepandabear

    02/07/2022, 3:56 AM
    Does anyone have any tips as to how I can improve this code? Something about it seems messy but I can't pinpoint what it is. I created my own
    FileHelperUtilities
    class in Kotlin to help with: • Saving a Bitmap as PNG/JPG • Opening an image from a URI with an
    Intent
    Code:
    bject FileHelperUtilities {
        fun saveBitmapAsImage(compressionOutputQuality: Int, compressionFormat: Bitmap.CompressFormat, onTaskFinished: (OutputCode, File) -> Unit, context: Context) {
            // Thanks to <https://stackoverflow.com/users/3571603/javatar> on StackOverflow - quite a bit of the code is based off of their solution
    
            var outputCode = OutputCode.SUCCESS
            val pathData = "image/jpeg"
            val outputName = if (compressionFormat == Bitmap.CompressFormat.PNG) "$projectTitle.png" else "$projectTitle.jpg"
    
            val environmentRoot = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString()
            val directory = File(environmentRoot)
    
            directory.mkdirs()
    
            val file = File(directory, outputName)
    
            try {
                val outputStream = FileOutputStream(file)
                val bitmapToCompress =  outerCanvasInstance.fragmentHost.drawToBitmap()
                bitmapToCompress.compress(compressionFormat, compressionOutputQuality, outputStream)
                outputStream.close()
            } catch (exception: Exception) {
                outputCode = OutputCode.FAILURE
            } finally {
                onTaskFinished(outputCode, file)
            }
    
            MediaScannerConnection.scanFile(context, arrayOf(file.path), arrayOf(pathData), null)
        }
    
        fun openImageFromUri(uri: Uri, onTaskFinished: (OutputCode) -> Unit, context: Context) {
            var outputCode = OutputCode.SUCCESS
            val intentAction = Intent.ACTION_VIEW
            val type = "image/*"
    
            val intent = Intent()
            intent.action = intentAction
            intent.setDataAndType(uri, type)
    
            try {
                context.startActivity(intent)
            } catch (exception: Exception) {
                outputCode = OutputCode.FAILURE
            } finally {
                onTaskFinished(outputCode)
            }
        }
    }
    Here it is in use:
    package com.realtomjoney.pyxlmoose.customviews.pixelgridview
    
    import android.graphics.Bitmap
    import android.net.Uri
    import com.realtomjoney.pyxlmoose.activities.canvas.projectTitle
    import com.realtomjoney.pyxlmoose.enums.OutputCode
    import com.realtomjoney.pyxlmoose.extensions.SnackbarDuration
    import com.realtomjoney.pyxlmoose.extensions.showSnackbar
    import com.realtomjoney.pyxlmoose.extensions.showSnackbarWithAction
    import com.realtomjoney.pyxlmoose.utility.FileHelperUtilities
    import java.io.File
    
    lateinit var file: File
    
    fun PixelGridView.extendedSaveAsPNG() {
       FileHelperUtilities.saveBitmapAsImage(90, Bitmap.CompressFormat.PNG, { outputCode, _file ->
           if (outputCode == OutputCode.SUCCESS) {
               file = _file
    
               showSnackbarWithAction("Successfully saved $projectTitle as PNG", SnackbarDuration.MEDIUM, "View") {
                   FileHelperUtilities.openImageFromUri(Uri.fromFile(file), { outputCode ->
                       if (outputCode == OutputCode.FAILURE) {
                           showSnackbar("Error trying to view file", SnackbarDuration.DEFAULT)
                       }
                   }, context)
               }
           } else {
               showSnackbar("Error saving $projectTitle as PNG", SnackbarDuration.DEFAULT)
           }
        }, context)
    }
    p
    • 2
    • 2
  • m

    Mark

    02/23/2022, 8:01 AM
    /**
     * usage: val regex by "foo".lazyRegex(RegexOption.IGNORE_CASE)
     * instead of:
     * val regex by lazy { "foo".toRegex(RegexOption.IGNORE_CASE) }
     * or:
     * val regex = "foo".toRegex(RegexOption.IGNORE_CASE)
     */
    fun String.lazyRegex(option: RegexOption? = null): Lazy<Regex> =
        lazy {
            if (option == null)
                toRegex()
            else
                toRegex(option)
        }
    So here, if you already have a bunch of properties like:
    val regex = "foo".toRegex()
    you can very easily convert to:
    val regex by "foo".lazyRegex()
    p
    r
    +2
    • 5
    • 43
  • t

    therealbluepandabear

    02/26/2022, 3:46 AM
    How good is this?
    import java.util.UUID
    
    enum class Color {
        RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE, TRANSPARENT
    }
    
    interface Shape {
        val name: String
        val uuid: UUID
            get() = UUID.randomUUID()
        val width: Int
        val height: Int
        val fillColor: Color
        val strokeThickness: Int
        val strokeColor: Color
        fun draw()
        fun erase()
    }
    
    class Square(
        override val width: Int,
        override val height: Int,
        override val fillColor: Color,
        override val strokeThickness: Int,
        override val strokeColor: Color
        ) : Shape {
        init {
            if (width != height) {
                throw IllegalArgumentException("Length must be equal to width.")
            }
        }
    
        override val name = "Square"
    
        override fun draw() {
            println("$name has been drawn.")
        }
    
        override fun erase() {
            println("$name has been erased.")
        }
    }
    
    class Rectangle(
        override val width: Int,
        override val height: Int,
        override val fillColor: Color,
        override val strokeThickness: Int,
        override val strokeColor: Color
        ) : Shape {
        override val name = "Rectangle"
    
        override fun draw() {
            println("$name has been drawn.")
        }
    
        override fun erase() {
            println("$name has been erased.")
        }
    }
    
    class Canvas(
        private val width: Int,
        private val height: Int,
        private val shapeData: MutableList<Shape>
        ) {
        init {
            for (shape in shapeData) {
                if (shape.width > this.width || shape.height > this.height) {
                    throw IllegalArgumentException("Shape of ${shape.uuid} is too large.")
                }
            }
        }
    
        fun eraseContents() {
            for (shape in shapeData) {
                shape.erase()
            }
        }
    
        fun drawContents() {
            for (shape in shapeData) {
                shape.draw()
            }
        }
    }
    k
    l
    • 3
    • 3
  • k

    KV

    03/02/2022, 2:11 PM
    Hello peps, I have a state class like below:
    data class ViewState(
        var startDateTime: LocalDateTime? = null,
        var endDateTime: LocalDateTime? = null,
        var totalBreakDuration: Duration? = null,
        var onEditClick: () -> Unit = {}
    ) {
        fun totalDuration() = startDateTime?.let { startDateTime ->
            endDateTime?.let { endDateTime ->
                Duration.between(startDateTime, endDateTime)
            }
        }
    
        fun workDuration() = totalDuration()?.minus(totalBreakDuration!!)
    }
    I have stateImplementation like Below:
    state.startDateTime?.let {
                        ViewItemState(
                            label = "label",
                            value = it.format(ISO_LOCAL_DATE)
                        )
                    }?.let(binding.dateItem::setupWithState)
    -----------------------------------------------------------------
                    state.startDateTime?.let {
                        ViewItemState(
                            label = "label"
                            value = it.format(ISO_LOCAL_TIME)
                        )
                    }?.let(binding.startTimeItem::setupWithState)
    -----------------------------------------------------------------------------
                    state.endDateTime?.let {
                        ViewItemState(
                            label = "label",
                            value = it.format(ISO_LOCAL_TIME)
                        )
                    }?.let(binding.endTimeItem::setupWithState)
    -----------------------------------------------------------------------------
                    state.totalDuration()?.let { DurationFormat().format(it) }?.let {
                        ViewItemState(
                            label = "label",
                            value = it
                        )
                    }?.let(binding.totalTimeItem::setupWithState)
    -----------------------------------------------------------------------------
                    state.totalBreakDuration?.let { DurationFormat().format(it) }?.let {
                        ViewItemState(
                            label = "label,
                            value = it
                        )
                    }?.let(binding.totalBreakTimeItem::setupWithState)
    -----------------------------------------------------------------------------
                    state.workDuration()?.let { DurationFormat().format(it) }?.let {
                        ViewItemState(
                            label = "label",
                            value = it
                        )
                    }?.let(binding.workTimeItem::setupWithState)
    • 1
    • 1
  • c

    Colton Idle

    03/16/2022, 2:40 AM
    This method works nicely if a person has a middle name, but if they don't. Then it print
    [FIRST]..[LAST]
    Notice the two dots are supposed to show that there are two spaces. What's a convenient way of only having a single space?
    private fun Person.prettyPrint() =
            "${this.data.firstName} ${this.data.middleName} ${this.data.lastName}"
    a
    r
    e
    • 4
    • 4
  • m

    marcinmoskala

    03/23/2022, 11:43 AM
    I am updating Effective Kotlin Item 33: Consider factory functions instead of secondary constructors. I changed that completely, may I ask for a feedback? https://docs.google.com/document/d/1jN6gltGAN6DMr-_sKoRFStVsaymp-V8ajYvDeVztKOo/edit?usp=sharing
    👍 1
    j
    • 2
    • 1
  • s

    Szymon Jeziorski

    03/27/2022, 11:55 AM
    Hello, I have a use case where I have 2 separate files witch expose public top-level functions (extension functions for mapping objects) calling private helper functions inside them. The issue is that some of those private functions duplicate and I would like to reuse them rather than copy-paste them and don't want to make them public so that they're visible from everywhere. The first thing that comes to my mind is OOP approach where I encapsulate those private functions to an abstract class, implement public extensions inside singleton objects inheriting this abstract class, and then import those extensions statically when used to work on them as on top-level functions. Example: SampleModifications.kt:
    abstract class SampleModifications {
        protected fun helper1(...) [...]
    
        protected fun SampleField.helper2(...) [...]
    }
    helpers usage: SampleMapper.kt
    object SampleMapper : SampleModifications() {
        fun Sample.toSomethingElse() = [...] // calling helper1 from SampleModifications inside
    
        [...]
    }
    extensions usage:
    import [...].SampleMapper.toSomethingElse
    
    [...]
    
    sampleRepository.findByIdOrNull(id)?.toSomethingElse()
    This works fine and does what I want but declaring abstract classes for such use case seems like overkill for me so wondering if I could achieve the same cleaner or maybe more idiomatic, how would you approach it?
    i
    a
    • 3
    • 2
  • m

    Mark

    04/01/2022, 9:19 AM
    Goal: lazy map (where we only need the getter) supporting multithreaded access. Is there a better way?
    val getValuesForKey: (String) -> Set<String> =
        object : (String) -> Set<String> {
            val map = mutableMapOf<String, Set<String>>()
    
            override fun invoke(key: String): Set<String> =
                synchronized(this) {
                    map.getOrPut(key) {
                        calculateValuesForKey(key)
                    }
                }
        }
    e
    • 2
    • 9
  • d

    Damiano Petrungaro

    04/02/2022, 12:25 AM
    Hey folks! Posting this message here as well, I think may be the better channel for the purpose of my message 😄
    Hello people!
    I am new to Kotlin 🔥
    I do have a Golang background, and I have to admit that I am enjoying it so far!
    I’d love if some of you would give me some feedback about this project I am doing just as a server for practicing Kotlin 🙂
    Let me know if you spot any bad practice in the source code, happy to receive some constructive feedback!
    a
    • 2
    • 7
  • l

    LeoColman

    04/03/2022, 4:51 PM
    Hey guys! I'd like to discuss the following syntaxes:
    fun insertAll(uses: Iterable<Use>) {
      uses.forEach { insert(it) }
      uses.forEach(::insert)
    }
    What do you think about both approaches?
    e
    • 2
    • 3
  • i

    ildar.i [Android]

    04/12/2022, 12:08 PM
    Could someone review our BaseViewModel on coroutines? It delegates all context handling to special object uiCaller, which enables composition of ViewModel logic
    BaseViewModel
    c
    j
    h
    • 4
    • 16
  • v

    Vivek Modi

    04/21/2022, 9:32 PM
    Hey Guys, I am working in ktor api response. I want to handle api response. So i read from some medium post. I tried some code. Can you suggest me if there is any better approach then this?
    package com.example.kotlinmultiplatformsharedmodule
     
     sealed class ApiResponse<out T : Any> {
     
         data class Success<out T : Any>(
             val data: T?
         ) : ApiResponse<T>()
     
         data class Error(
             val exception: Throwable? = null,
             val responseCode: Int = -1,
             val errorResponse: ErrorResponse? = null
         ) : ApiResponse<Nothing>()
     
         fun handleResult(onSuccess: ((responseData: T?) -> Unit)?,onError: ((error: Error) -> Unit)?) {
             when (this) {
                 is Success -> {
                     onSuccess?.invoke(this.data)
                 }
                 is Error -> {
                     onError?.invoke(this)
                 }
             }
         }
     }
     
     data class ErrorResponse(
         val errorCode: Int,
         val errorMessage: String
     )
    r
    • 2
    • 2
  • i

    Ink

    04/24/2022, 5:38 PM
    Hi guys, how can I refactor that code?
    val productShopInfoItems = productListItemMapper.toShopInfoItems(it.snapshot)
    
    state.productList.value?.forEach { product ->
        productShopInfoItems.forEach {  shop ->
            if(product.productId == shop.productId){
                product.shopInfoItemList += shop
            }
        }
    }
    product is
    data class ProductItem(
        val productId: String = "",
        val productName: String = "",
        var shopInfoItemList: List<ShopInfoResponseItem> = emptyList<ShopInfoResponseItem>()
    )
    r
    • 2
    • 2
  • e

    Ellen Spertus

    05/09/2022, 1:40 AM
    I'm modifying some code that looks like this (middle 8 lines omitted):
    dialpad_0_holder.setOnClickListener { dialpadPressed('0', it) }
    dialpad_9_holder.setOnClickListener { dialpadPressed('9', it) }
    If the flag
    tremor
    is
    true
    , I would like to call
    setOnLongClickListener
    instead of
    setOnClickListener
    . Is it possible to do something like this?
    val f = if (tremor) RelativeLayout.onLongClickListener else RelativeLayout.onClickListener
    dialpad_0_holder.f { dialpadPressed('0', it) }
    dialpad_9_holder.f { dialpadPressed('9', it) }
    e
    • 2
    • 10
  • e

    Ellen Spertus

    05/16/2022, 8:01 PM
    Which is better and why? 1️⃣ This is broken
    return binding.myField.getWidth() != 0 ? binding.myField.getWidth() : binding.otherField.getWidth()
    2️⃣
    return binding.myField.getWidth().let {
        if (it != 0) it else binding.otherField.getWidth()
    }
    3️⃣ by @Luke
    return if (binding.myField.getWidth() != 0) binding.myField.getWidth() else binding.otherField.getWidth()
    l
    k
    • 3
    • 7
  • v

    Vivek Modi

    05/17/2022, 9:31 AM
    Good Morning guys, What is the best approach to find three items in single list. I tried some code and working fine. I want to know is there any better approach for this
    val completeEvent = events?.lastOrNull { events -> events.status == "complete" }
    val activeEvent = events?.find { events -> events.status == "active" }
    val futureEvent = events?.firstOrNull { events -> events.status == "future" }
    ApiResponse
    "Events": [{
    			"title": "Test 1",
    			"status": "complete"
    		}, {
    			"title": "Test 2",
    			"status": "complete"
    		}, {
    			"title": "Test 3",
    			"status": "complete",
    		}, {
    			"title": "Test 4",
    			"status": "complete"
    		}, {
    			"title": "Test 5",
    			"status": "complete"
    		}, {
    			"title": "Test 6",
    			"status": "active"
    		}, {
    			"title": "Test 7",
    			"status": "future"
    		}, {
    			"title": "Test 8",
    			"status": "future"
    		}]
    k
    r
    • 3
    • 5
  • j

    Jorge Domínguez

    05/17/2022, 7:59 PM
    Hi all, is it possible to rewrite this in a better way?
    fun SomeEnum.getImageRes(
        param: SomeOtherEnum
    ): Int {
        return when (param) {
            SomeOtherEnum.OtherEnumA -> {
                when (this) {
                    SomeEnum.EnumA -> R.drawable.res1_a
                    SomeEnum.EnumB -> R.drawable.res1_b
                }
            }
            SomeOtherEnum.OtherEnumB -> {
                when (this) {
                    SomeEnum.EnumA -> R.drawable.res2_a
                    SomeEnum.EnumB -> R.drawable.res2_b
                }
            }
        }
    }
    j
    p
    • 3
    • 11
  • n

    nikolaymetchev

    06/01/2022, 10:32 AM
    Would anyone have an opinion if these 2 functions combining
    use
    and
    with
    should be added to the standard library:
    inline fun <T : AutoCloseable?, R> T.useWith(block: T.() -> R): R = use(block)
    inline fun <T : Closeable?, R> T.useWith(block: T.() -> R): R = use(block)
    k
    • 2
    • 5
  • m

    Mark

    06/04/2022, 4:30 AM
    Looking for feedback on naming and implementation. If all items transform to the same value, then that value is returned, otherwise null
    fun <T, R> Iterable<T>.singleOrNullBy(transform: (T) -> R): R? {
        if (this is Collection && this.isEmpty()) return null
        return asSequence()
            .map(transform)
            .zipWithNext()
            .map { (a, b) -> if (a == b) a else null } // important we don't use mapNotNull here
            .distinct()
            .singleOrNull()
    }
    e
    • 2
    • 13
  • m

    Mark

    06/07/2022, 2:05 AM
    fun <T> Iterable<T>.splitByIndex(index: Int): Pair<List<T>, List<T>> {
        if (index <= 0) {
            return emptyList<T>() to this.toList()
        }
        val iterator = this.iterator()
        val firstList = mutableListOf<T>()
        val secondList = mutableListOf<T>()
        var activeList = firstList
        while (iterator.hasNext()) {
            if (activeList.size == index) {
                activeList = secondList
            }
            activeList.add(iterator.next())
        }
        return firstList to secondList
    }
    Is it okay to check the
    size
    each time or better to maintain a local
    Int
    count?
    e
    • 2
    • 15
Powered by Linen
Title
m

Mark

06/07/2022, 2:05 AM
fun <T> Iterable<T>.splitByIndex(index: Int): Pair<List<T>, List<T>> {
    if (index <= 0) {
        return emptyList<T>() to this.toList()
    }
    val iterator = this.iterator()
    val firstList = mutableListOf<T>()
    val secondList = mutableListOf<T>()
    var activeList = firstList
    while (iterator.hasNext()) {
        if (activeList.size == index) {
            activeList = secondList
        }
        activeList.add(iterator.next())
    }
    return firstList to secondList
}
Is it okay to check the
size
each time or better to maintain a local
Int
count?
e

ephemient

06/07/2022, 2:09 AM
for a
List
it is definitely more efficient to use
fun <T> List<T>.splitAt(index: Int) = take(index) to drop(index)
since that uses
.subList()
underneath which most
List
implementations override (e.g.
ArrayList
which returns a view with no extra allocation)
👍 2
and for a not-
List
index
is usually not very meaningful
…hmm, I thought it used
subList
but it doesn't seem to after all
slice
does, though
m

Mark

06/07/2022, 2:14 AM
Yes, I was just looking at
Iterable.take()
and I noticed something else:
if (this is Collection<T>) {
    if (n >= size) return toList()
    if (n == 1) return listOf(first())
}
Doesn’t that second line run into the problem you mentioned earlier?
e

ephemient

06/07/2022, 2:15 AM
yep
sometimes those trade-offs are acceptable - in almost all cases, concurrent modification of a data structure is a broken idea. I specifically use
CopyOnWriteArrayList
because it's one of the few data structures that actually has well-defined and useful behavior on concurrent modification. I would write generic code to make as few assumptions about the underlying data as possible, but it seems kotlin.collections is more optimized around non-mutating collections - which is probably reasonable for most Kotlin applications
(e.g. if you were to mutate a
mutableListOf(...)
in one thread while reading it in another, there's no guarantees about consistency whatsoever, regardless of how safe the reader code is; it's only specific concurrent collections such as
CopyOnWriteArrayList
which promise
iterator()
stability)
👍 1
m

Mark

06/07/2022, 2:23 AM
fun <T> Iterable<T>.splitAt(index: Int): Pair<List<T>, List<T>> {
    if (index <= 0) {
        return emptyList<T>() to this.toList()
    }
    if (this is List) { // optimization to avoid iterator
        val safeList = this.toList()
        if (index >= safeList.size) {
            return safeList to emptyList()
        }
        return safeList.subList(0, index) to safeList.subList(index, safeList.size)
    }
    val iterator = this.iterator()
    val firstList = mutableListOf<T>()
    val secondList = mutableListOf<T>()
    var activeList = firstList
    while (iterator.hasNext()) {
        if (activeList.size == index) {
            activeList = secondList
        }
        activeList.add(iterator.next())
    }
    return firstList to secondList
}
BTW, I do have a use case for non-Lists. For example, a sorted set where you want to take the first few items and also do something with the remainder. I suppose to be ultra safe, I should convert the
List
using
toList()
and only then apply
subList
(UPDATED CODE)
e

ephemient

06/07/2022, 2:33 AM
sure, that's one approach. I would tend to prefer
buildList {
    repeat(index) {
        if (!iterator.hasNext()) return@buildList
        add(iterator.next())
    }
} to buildList {
    while (iterator.hasNext()) add(iterator.next())
}
but you could even do tricks like
Iterable { iterator }.take(index) to Iterable { iterator }.toList()
👍 2
m

Mark

06/07/2022, 2:33 AM
Hmm, so perhaps even create the
safeList
anyway straight after the initial index check
fun <T> Iterable<T>.splitAt(index: Int): Pair<List<T>, List<T>> {
    if (index <= 0) {
        return emptyList<T>() to this.toList()
    }
    val safeList = this.toList()
    if (index >= safeList.size) {
        return safeList to emptyList()
    }
    return safeList.subList(0, index) to safeList.subList(index, safeList.size)
}
e

ephemient

06/07/2022, 2:35 AM
I think there's a few other places in stdlib which do a similar defensive copy to an Array, but generally you don't need to go for that
there isn't really much difference between doing the iteration yourself and the list copy, both of them go through the iterator once
m

Mark

06/07/2022, 2:37 AM
Yeah fair enough, but less code
subList
returns a view on the original list, so that may be why it’s better to first create a read-only list, but actually I prefer your idea:
fun <T> Iterable<T>.splitAt(index: Int): Pair<List<T>, List<T>> {
    if (index <= 0) {
        return emptyList<T>() to this.toList()
    }
    val iterator = iterator()
    return Iterable { iterator }.take(index) to Iterable { iterator }.toList()
}
View count: 2