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

    Byron Katz

    05/21/2021, 5:50 PM
    Why does Jacoco think there are six branches?
    e
    g
    • 3
    • 4
  • h

    hho

    05/25/2021, 4:56 PM
    Is there a better (or "more Kotlin") way to get an enum value when I don't have a concrete type? It feels weird having to resort to
    java.lang.Enum
    ...
    sealed class EnumBinding<E : Enum<E>>(
    	private val enumType: Class<E>
    ) : Binding<Any?, E?> {
    
    	override fun converter(): Converter<Any?, E?> = object : Converter<Any?, E?> {
    		override fun from(databaseObject: Any?): E? =
    			databaseObject?.let { java.lang.Enum.valueOf(enumType, it.toString()) }
            …
        }
        …
    }
    (it's a custom jOOQ binding, so I can't change
    Binding
    or
    Converter
    )
    e
    m
    • 3
    • 6
  • k

    KV

    06/16/2021, 1:41 PM
    What is the best way to write the below code?
    viewLifecycleOwner.lifecycleScope.launch {
                viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                    launch {
                        collectABCState()
                    }
    
                    launch {
                        collectABCInfo()
                    }
    
                    launch {
                        collectXYZFailedEvents()
                    }
    
                    launch {
                        collectABCTime()
                    }
    
                    launch {
                        collectABCSummary()
                    }
                }
    e
    • 2
    • 1
  • a

    Andrew K

    06/24/2021, 12:00 AM
    How can I allow this to accept a String in the
    find
    extension in addition to an Int? Is there anything else I can do to optimize as well?
    infix fun <T> T?.ifNull(block: () -> T?) = this ?: block()
    
    inline fun <reified T> EnumCompanion<T>.find(value: Int): T? where T : Enum<T>, T : EnumValue<T> =
        enumValues<T>().run {
            firstOrNull { (it.value as Int) == value }
                .ifNull { firstOrNull { it.name == "Unknown" } }
                .ifNull { throw Exception("Enum value does not exist") }
        }
    
    interface EnumCompanion<T : Enum<T>>
    
    interface EnumValue<T> {
        val value: T
    }
    
    enum class MyEnum(override val value: Int) : EnumValue<Int> {
        Unknown(0),
        First(1),
        Second(2),
        Third(3);
    
        companion object : EnumCompanion<MyEnum>
    }
    
    MyEnum.find(1)
    m
    • 2
    • 1
  • h

    hho

    06/28/2021, 4:08 PM
    Kotlin has 1️⃣
    check(…)
    and 2️⃣
    require(…)
    . Which would be better to signal an invalid configuration (i.e. on startup)? Or should I make up 3️⃣ my own exception class? I'm really torn between "a bad config is an illegal argument" and "the app is in an illegal state and can't start" 😕
    z
    • 2
    • 3
  • o

    oday

    07/06/2021, 11:19 AM
    I’m at a loss here, what is wrong with this code? what’s wrong with the Stack I’ve implemented ? https://paste.ofcode.org/MmxwVcvXvdBY5EZfZpTPWS the moment I use Java’s own Stack, the function works fine and returns true for 1st test and false for 2nd
    t
    • 2
    • 7
  • k

    KV

    07/28/2021, 8:40 AM
    How to write this method in better way?
    /** Returns the signed in users ID as a `String` or `null` if no ID in shared preferences found (or `0`). */
    
    fun SharedPreferencesManager.userId(): String? {
        val userIdLong: Long = this.loadCurrentAdminPsid()
        return if (userIdLong == 0L) null else userIdLong.toString()
    }
    e
    e
    m
    • 4
    • 5
  • n

    Nick

    08/18/2021, 3:18 PM
    I have a property called captureMode which observes on a camera
    StateFlow
    and change it’s value when the camera changes. Additionally, I want to be able to set captureMode manually. But since captureMode is a stateFlow, I can’t set it. Is there a better way?
    Untitled.kt
    e
    • 2
    • 3
  • b

    bodiam

    09/01/2021, 12:32 PM
    Hi all, I’ve created a small DSL, but my challenge is that I need a reference to some of the items in the tree I’m building, and I was wondering if you have any suggestions on how to do this. This is my current DSL:
    lateinit var childFolder1 : FolderNode
             lateinit var childFolder2 : FolderNode
    
             val rootFolder = buildFolders(am,"System") {
                childFolder1 = folder("A") {
                    +entry(Attribute("x"), Sample("1"))
                }
                childFolder2 = folder("A") {
                    +entry(Attribute("x"), Sample("2"))
                    +entry(Attribute("x"), Sample("2"))
                }
    
                +childFolder1
                +childFolder2
            }
    
            println(childFolder1) // simplified here
    As you can see, I need a reference to childFolder1 in my code, but my current solution seems a bit non-idiomatic, so I was wondering if you have any suggestions on how to improve this? (I’m also not sure if this is the right channel, the new setup confuses me a bit, so if I need to post this somewhere else, please let me know)
    p
    • 2
    • 2
  • s

    sbyrne

    09/02/2021, 12:52 PM
    I wrote these so I can chain casts so I can avoid the parenthesis involved in using
    as?
    . Is there a better way to chain casts, or something similar in the stdlib that I missed?
    Untitled.kt
    s
    • 2
    • 1
  • j

    Jukka Siivonen

    09/07/2021, 1:36 PM
    Any ideas to make this more compact or idiomatic?
    s
    c
    +2
    • 5
    • 10
  • r

    rocketraman

    09/09/2021, 7:46 PM
    I have a function that maps a sealed exception type
    ServiceException
    to an implementation of some sealed payload interface
    T
    e.g.:
    inline fun <reified T> ServiceException.toError(): T {
      return when(this) {
        is InvalidInputException -> InvalidInputError(...)
        is PermissionDeniedException -> PermissionDeniedError(...)
      } as T
    }
    The payload type
    T
    is some interface. I can cast the result of the
    when
    to T as shown, but then forgetting to implement
    T
    in each of these error types will result in a run-time exception. What would be the best way to create a re-usable function here that is compile-time type-validated, just as if that function were literally inlined?
    u
    • 2
    • 4
  • s

    Simon Lin

    09/10/2021, 8:43 AM
    Is there a better way to check a string contains both number and alphabet?
    val text = "aas211w"
    if (text.any { it.isDigit() } && text.any { it.isLetter() }) {
    }
    e
    t
    +3
    • 6
    • 10
  • s

    smallufo

    09/17/2021, 5:29 PM
    Hi , Is there any way to intercept method from interface and cache result “WITHOUT” spring’s method cache ? Take a simple calculator for example :
    interface ICalculate {
    
      fun multiply(a: Int, b: Int): Int
    }
    It just multiplies
    a
    and
    b
    , and return the result . Suppose it is a heavy computation work . And there are two implementations :
    class CalculatorDumb : ICalculate {
      override fun multiply(a: Int, b: Int): Int {
        var sum = 0
        (1..a).forEach {
          (1..b).forEach {
            sum++
          }
        }
        return sum
      }
    }
    The dumb implementation just add one by one .
    class CalculatorSmart : ICalculate {
    
      override fun multiply(a: Int, b: Int): Int {
        return a * b
      }
    }
    And this smart implementation just returns
    a * b
    . OK , here is the point . I hope client can initialize no matter dumb or smart implementation , and can get result if the parameter is identical. There is a
    Memoize
    pattern , described here : https://jorgecastillo.dev/kotlin-purity-and-function-memoization :
    class Memoize<in T, out R>(val f: (T) -> R) : (T) -> R {
      private val values = mutableMapOf<T, R>()
      override fun invoke(x: T): R {
        return values.getOrPut(x) { f(x) }
      }
    }
    
    fun <T, R> ((T) -> R).memoize(): (T) -> R = Memoize(this)
    I can use it in the implementation class , like this :
    class CalculatorSmart : ICalculate {
    
      data class CacheKey(val a: Int, val b: Int)
    
      private val innerCalculate: (CacheKey) -> Int = { key: CacheKey ->
        println("cache miss")
        key.a * key.b
      }.memoize()
    
      override fun multiply(a: Int, b: Int): Int {
        return innerCalculate(CacheKey(a, b))
      }
    }
    But it seems it’s hard to apply it in the interface layer. I wonder if there are any patterns to achieve : 1. Each implementation class ( dumb or smart in this example) doesn’t need to implement its cache . 2. There are no two versions of method (
    multiply()
    and
    cachedMultiply()
    for example ) 3. Client only knows one method of the interface , No matter the client initialize smart or dumb class , the result of the same parameter will be cached and returned. For example : such scenario is OK
    val calSmart: ICalculate = CalculatorSmart()
    println(calSmart.multiply(3, 7)) // cache miss
    println(calSmart.multiply(3, 7)) // cache hit
    
    val calDumb: ICalculate = CalculatorDumb()
    println(calDumb.multiply(3, 7)) // cache miss
    println(calDumb.multiply(3, 7)) // cache hit
    It will work like Spring’s method cache . but I hope there will be a kotlin-idiomatic style , maybe more functional , just like the memoization pattern above . Is there any idea ? Thanks.
    j
    e
    • 3
    • 3
  • t

    therealbluepandabear

    09/22/2021, 11:55 PM
    Anyone know a faster and more efficient way to check if a given word is a shuffled version of another given word? Here's my current code:
    fun String.checkIfShuffledVersionOfAns(ans: String): Boolean {
        val listOfChars = this.toCharArray()
        val shuffledListOfStrings = mutableListOf<String>()
    
        var iterations = 0
    
        while (iterations < 100000) {
            listOfChars.shuffle()
            if (!shuffledListOfStrings.distinct().contains(listOfChars.concatToString())) {
                shuffledListOfStrings.add(listOfChars.concatToString())
            }
            iterations++
        }
    
        for (string in shuffledListOfStrings.distinct()) {
            if (string == this) return true
        }
    
        return false
    }
    e
    p
    +4
    • 7
    • 27
  • l

    louiscad

    09/24/2021, 9:56 AM
    Hello, I'm modeling the different types of audio focus as a Kotlin type hierarchy, and I'm unsure about picking
    sealed interface
    or
    sealed class
    . What would you pick? Any reason beyond personal preference? 1️⃣ Here's with `interface`:
    sealed interface AudioFocus {
        object Gain : AudioFocus
        sealed interface Loss : AudioFocus {
            companion object : Loss
            sealed interface Transient : Loss {
                companion object : Transient
                object CanDuck : Transient
            }
        }
    }
    2️⃣ Here's with `class`:
    sealed class AudioFocus {
        object Gain : AudioFocus()
        sealed class Loss : AudioFocus() {
            companion object : Loss()
            sealed class Transient : Loss() {
                companion object : Transient()
                object CanDuck : Transient()
            }
        }
    }
    2️⃣ 2
    1️⃣ 3
    j
    e
    z
    • 4
    • 8
  • d

    Dipendra Singh

    09/28/2021, 8:47 PM
    Hello, Im looking for a way to clean this code. I dont like this part of init empty String, is there other way write this?
    fun getStreetNameByStreetId(id: String): String {
            val query = Query()
            query.fields().include("name")
            query.addCriteria(Criteria.where("_id").`is`(id))
            var streetName = ""
            mongoTemplate.executeQuery(
                query, STREET_COLLECTION
            ) { document: Document ->
                streetName = document.getValue("name").toString()
            }
            return streetName
        }
    s
    p
    t
    • 4
    • 9
  • m

    Michael Böiers

    09/29/2021, 11:17 AM
    Is there any way to get lazy int ranges in Kotlin? I’m currently writing code like
    (1..n).asSequence()
    and it’s really annoying that you always have to clutter the code with the
    asSequence()
    call to make it lazy (read: perform well). EDIT: Yes, that came across the wrong way … lazy evaluation isn’t always better. 🙂
    m
    p
    +2
    • 5
    • 24
  • b

    Ben Madore

    09/30/2021, 5:48 PM
    i’ve got a class like:
    class MyFoo(
        val title:  String,
        val client: Foo = (some default)
    ) {...}
    I want to provide a default value of Foo when if it’s not provided, but it’s nontrivial to create a valid instance, and requires storing an instance variable e.g.
    val x = Bar()
    client = Foo.builder().bar(x).baz(Baz.builder().bar(x).build()).build()
    i’m struggling to figure out if this is possible with initializer / secondary constructors, without having to make
    client
    a nullable
    var
    .
    e
    s
    • 3
    • 4
  • j

    jimn

    10/11/2021, 3:58 PM
    works good! Softref holds the String pinning the weakref 😛
    val bolCache: MutableMap<String, SoftReference<Pai2<RowVec, String>>> = WeakHashMap(0)
    t
    • 2
    • 5
  • j

    Jonathan Mew

    10/11/2021, 4:29 PM
    Hoping to do away with an unchecked cast - any thoughts?
    @Suppress("UNCHECKED_CAST")
    fun <IdType> createWidgetFactory(cls: KClass<out IdType>): WidgetFactory<IdType> =
        when (cls) {
            IdA::class -> WidgetFactoryA() as WidgetFactory<IdType>
            IdB::class -> WidgetFactoryB() as WidgetFactory<IdType>
            else -> throw UnsupportedOperationException("Unknown WidgetFactory type!")
        }
    j
    t
    • 3
    • 3
  • m

    marcinmoskala

    10/18/2021, 5:04 PM
    [RFC] I consider adding the following item to the Effective Kotlin. What do you think? (I hope it is a right place for RFC) https://kt.academy/article/ek-operators
    t
    • 2
    • 2
  • m

    myanmarking

    10/21/2021, 3:22 PM
    is there any better way of improving this code. For example, using some std extension function idk:
    fun addChatHeaders(itemList: List<ChatMessage>): List<HelpCenterChatItem> {
        return buildList {
            itemList.forEachIndexed { index, item ->
                val current: ChatMessage = item
                val previous: ChatMessage? = itemList.getOrNull(index - 1)
    
                if (previous == null || (previous.date.dayOfYear != current.date.dayOfYear)) {
                    add(
                        HelpCenterChatItem.HeaderDate(
                            dateFormatter.format(
                                current.date,
                                DatePattern.ISO_DAY_MONTH_YEAR_SLASHED
                            )
                        )
                    )
                }
                add(current)
            }
        }
    }
    p
    k
    +3
    • 6
    • 8
  • j

    jwass

    10/27/2021, 1:56 PM
    Hello! I have a number of classes that might or might not be resolved to some external data source. So that just means wrapping in a container. A combination of optional / decorator pattern.
    sealed class Resolvable<T>
    class Resolved<T>(val value: T, val pk: Long) : Resolvable<T>()
    class Unresolved<T>(val value: T) : Resolvable<T>() {
        fun resolved(pk: Long) = Resolved(value, pk)
    }
    Now I want to take a
    Collection<Resolvable<ItemIdentifier>>
    and filter only unresolved ones, into a
    Collection<Unresolved<ItemIdentifier>>
    . This works:
    val x : Collection<Unresolved<ItemIdentifier>> = itemIdentifiers.mapNotNull { when(it) {is Unresolved -> it else -> null }}
    But I wonder if there's a more idiomatic way to do it? (type annotation on
    x
    just for clarity).
    o
    d
    t
    • 4
    • 10
  • k

    K Merle

    10/28/2021, 5:15 PM
    Any suggestions on how to improve my custom navigation animations? I've wrapped them inside a composable function.
    • 1
    • 1
  • t

    therealbluepandabear

    10/29/2021, 8:47 AM
    Which one? 1.
    class SnackbarUtils {
        companion object {
            fun makeSnackbar() {
    
            }
        }
    }
    2.
    class SnackbarUtils {
        fun makeSnackbar() {
    
        }
        companion object {
            val instance get() = SnackbarUtils()
        }
    }
    3.
    class SnackbarUtils {
        fun makeSnackbar() {
    
        }
        companion object {
            val instance = SnackbarUtils()
        }
    }
    3️⃣ 1
    j
    m
    c
    • 4
    • 45
  • h

    hisham bin awiad

    10/31/2021, 1:16 PM
    Hi guys .... hope you doing will what is the diff and what should i choose
    private val empID 
                 get() = (userModelId ?: session.getUserModelId().toSafetyString()).toSafetyString()
    
    	private val empID2 by lazy { (userModelId ?: session.getUserModelId().toSafetyString()).toSafetyString()  }
    s
    r
    m
    • 4
    • 7
  • i

    ivano

    11/05/2021, 1:24 PM
    Hi this is horrible do you know a more elegant way to refactor that ? ( sorry cor the format i am on mobile the three format ``` are not picked up) if (count() > 5) take(5).forEach { firstFiveSubsectionItems -> buildAlwaysVisibleLogic(alwaysVisibleView, firstFiveSubsectionItems) } else { forEach { itemsSubsection -> buildAlwaysVisibleLogic(alwaysVisibleView, itemsSubsection) } }
    s
    a
    • 3
    • 4
  • l

    LastExceed

    11/09/2021, 5:44 PM
    debugging challenge:
    fun main() {
        val root = Thing(null, 0).apply {
            addChild(1) {
                addChild(2)
                addChild(3) {
                    addChild(4)
                }
            }
            addChild(5)
        }
        root.printTree()
    }
    
    abstract class Nestable(
        val parent: Nestable?
    ) {
        val children = mutableListOf<Nestable>()
    }
    
    class Thing(
        parent: Thing?,
        val number: Int
    ) : Nestable(parent) {
        init {
            parent?.children?.add(this)
        }
    
        fun addChild(
            number: Int,
            block: Nestable.() -> Unit = {}
        ) = Thing(this, number).run(block)
    
        fun printTree(indentation: Int = 0) {
            println(" ".repeat(indentation) + number)
            children.forEach {
                (it as? Thing)?.printTree(indentation + 1)
            }
        }
    }
    expected output:
    0
     1
      2
      3
       4
     5
    actual output:
    0
     1
     2
     3
     4
     5
    find the bug >:)
    p
    k
    j
    • 4
    • 6
  • c

    Colton Idle

    11/16/2021, 5:24 PM
    Is there a better (more functional way) to write this?
    people.addAll(
        getAllPeople().map { Pair(it.first.orEmpty(), it.last.orEmpty()) }
    )
    I basically have a variable called people which is a Pair<>, and then I have the return of getAllPeople which is a Person.
    p
    j
    +3
    • 6
    • 20
Powered by Linen
Title
c

Colton Idle

11/16/2021, 5:24 PM
Is there a better (more functional way) to write this?
people.addAll(
    getAllPeople().map { Pair(it.first.orEmpty(), it.last.orEmpty()) }
)
I basically have a variable called people which is a Pair<>, and then I have the return of getAllPeople which is a Person.
p

Paul Griffith

11/16/2021, 5:29 PM
getAllPeople()
only ever returns a 2 element list?
❓ 1
or
getAllPeople()
returns
List<Pair<String, String>>
and you want
people
to be a
List<Person>
?
no, the opposite of this?
the obvious thing to do is to initialize
people
entirely in the
map
call:
val people = getAllPeople().map { it.first to it.last }
👍 1
c

Colton Idle

11/16/2021, 5:34 PM
sorry, first and last are firstName and lastName. So I'm mapping all of the people that come from getAllPeople into Pairs.
p

Paul Griffith

11/16/2021, 5:35 PM
https://pl.kotl.in/_jfF3bU9n
that's about how I'd do it, under the assumption it doesn't make sense for your purposes to have someone with an empty first or last name (which may or may not be true)
(see also: https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/)
👍 2
j

Joffrey

11/16/2021, 5:52 PM
I basically have a variable called people which is a Pair<>, and then I have the return of getAllPeople which is a Person.
You mean lists of those things, right?
p

Paul Griffith

11/16/2021, 5:54 PM
on a meta-level, I'm kinda curious why you're after this - I find Pair less ergonomic to use, and if you've already got a named class with useful members it's probably easier to hand that around
➕ 4
w

wbertan

11/16/2021, 5:56 PM
I would write something like this:
data class People(val firstName: String?, val lastName: String?)
fun getAllPeople(): List<People> = emptyList()
fun asas() {
    val people = mutableListOf<Pair<String, String>>()
//    people.addAll(
//        getAllPeople().map { Pair(it.firstName.orEmpty(), it.lastName.orEmpty()) }
//    )
    getAllPeople()
        .map { it.firstName.orEmpty() to it.lastName.orEmpty() }
        .let(people::addAll)
}
For me the reason would be to read first what is happening first, so basically
getAllPeople
, then
map
, the
people.ddAll
. But I would try to avoid the mutable list anyway, which would make it nicer to read from the begin. Anyway, my only suggestion here would be if you could potentially avoid mutability and perhaps can use immutable data there? Also what @Paul Griffith said above.
k

Klitos Kyriacou

11/16/2021, 8:54 PM
When dealing with Pair(firstName, lastName), I wouldn't use the
to
infix function to create the pair. The word "to" implies a key-value relationship. First name does not map to surname; it's just a pair of names. Therefore I would use Pair(firstName, lastName) even though it's slightly longer. It's more readable.
:nice: 1
➕ 1
r

rook

11/17/2021, 4:48 PM
getAllPeople().mapTo(people){...}
👍 1
➕ 1
c

Colton Idle

11/17/2021, 9:58 PM
I really like mapTo!! Thanks that's pretty much what my question was really asking. How can I map one list of A to a list of B.
j

Joffrey

11/17/2021, 10:01 PM
But most of the time you should use read-only lists instead of a mutable list. So
val mappedList = sourceList.map { ... }
is preferable over creating a mutable list first and then using
mapTo
➕ 2
I'm still quite curious (like @Paul Griffith ) as to why you want to map those objects to the lesser
Pair
. It would seem better to make the properties of
Person
non nullable in the first place, or to create an equivalent data class with non-nullable fields if you really need the current
Person
class
p

Paul Griffith

11/17/2021, 10:03 PM
yeah, the 'more functional' way to do things is to not have side effects - the transformation of A to B should be the function, and
map
should be used to apply it.
mapTo
is useful if, say, you have a collection with some elements already (that you can't fit into your starting collection) or something like that, but in the problem described, you don't need (and should avoid) creating the list and then populating it in two steps
👍 1
c

Colton Idle

11/17/2021, 10:08 PM
Interesting. My example I gave isn't what I'm actually using in real life, it's just as simple of an example as I could come up with. But for example, some real life examples is that I have a call to getAllMovies() and that gives me back a list of MovieDTO. Now I want to map my MovieDTOs into MovieUI objects. So I'm just looking for how to map between two very similar classes, but are different classes.
j

Joffrey

11/17/2021, 10:11 PM
Ok that answers the
Pair
stuff then. The
mapTo
vs
map
still holds, though. In the case you mention, you should use
map
.
c

Colton Idle

11/17/2021, 10:18 PM
Okay. So if my map just transforms from ObjectA to ObjectB, then the output will just be a List<ObjectB> and then I can addAll to my variable of listOfObjectB?
j

Joffrey

11/17/2021, 10:30 PM
Sorry if I was unclear. If your goal really is to add to a mutable list, then of course
mapTo
is what should be used instead to avoid an extra list. But our point was that if you don't already have a mutable list, you should probably not create a mutable list at all and just use the result of map directly
View count: 3