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

    Jitendra

    07/20/2022, 10:56 AM
    I Am trying to write UI testing in one of my compose project, can some one suggest best library to write this, previously we use robolectric
  • l

    Lucas

    07/20/2022, 1:48 PM
    Can anyone tell me what is wrong with this?
    c
    m
    • 3
    • 7
  • j

    Jasmin Fajkic

    07/20/2022, 7:20 PM
    I get date as string from backend and now at first I need to convert it to date time and then to compare this date and current date difference in years, months, weeks, days, minutes and seconds. In JS I can do this easily with moment JS like this
    function extractTime(time) {
      return {
        seconds: moment().diff(time, 'seconds'),
        minutes: moment().diff(time, 'minutes'),
        hours: moment().diff(time, 'hours'),
        days: moment().diff(time, 'days'),
        weeks: moment().diff(time, 'weeks'),
        months: moment().diff(time, 'months'),
        years: moment().diff(time, 'years'),
      };
    }
    Is there something similar in Kotlin that I can achieve same result?
    m
    m
    +2
    • 5
    • 5
  • l

    Lukasz Kalnik

    07/22/2022, 11:53 AM
    Is this how you return an empty lambda from an
    if ... else
    expression?
    val myLambda: () -> Unit = if (condition) doSomethingLambda else {{}}
    j
    s
    • 3
    • 15
  • n

    nkiesel

    07/23/2022, 1:22 AM
    I have a tree represented by a Map<String, String> mapping child node it to parent node id. I now want to compute all the paths for this tree, starting at given node of the tree. Right now I have the following code, but I have the nagging feeling that I'm missing some more functional approach for this:
    val tree = mapOf(2 to 1, 3 to 2, 4 to 3, 5 to 1)
    
    fun allPath(tree: Map<Int, Int>, root: Int): Map<Int, List<Int>> {
        return (tree.keys.associateWith { path(it, tree, root) } + mapOf(root to listOf(root))).filterValues { it.isNotEmpty() }
    }
    
    fun path(start: Int, tree: Map<Int, Int>, root: Int): List<Int> {
        return buildList {
            var n: Int? = start
            while (n != null && n != root) { add(n); n = tree[n] }
            if (n == null) return emptyList()
            add(root)
        }.reversed()
    }
    
    println(allPath(tree, 1)) // prints {2=[1, 2], 3=[1, 2, 3], 4=[1, 2, 3, 4], 5=[1, 5], 1=[1]}
    e
    m
    • 3
    • 5
  • c

    Colton Idle

    07/23/2022, 4:02 AM
    Am I using sealed classes correctly in this scenario?
    sealed interface UserType {
      object GUEST : UserType
      class AUTHENTICATED(
        val authToken: String,
      ) : UserType
    }
    d
    e
    • 3
    • 3
  • z

    zero_coding

    07/23/2022, 7:39 AM
    https://stackoverflow.com/questions/73086295/composite-id-class-must-implement-serializable-io-digiwave-entities-storeentity
  • z

    zero_coding

    07/23/2022, 7:40 AM
    Would be happy if someone can help
  • c

    Colton Idle

    07/24/2022, 9:38 PM
    I have found myself writing some snippets similar to this. Is there a better way to do it?
    fun updateUser(username: String? = null, email: String? = null, token: String? = null) {
      if (username != null) {
        _appUser.value = _appUser.value?.copy(username = username)
      }
      if (email != null) {
        _appUser.value = _appUser.value?.copy(email = email)
      }
      if (token != null) {
        _appUser.value = _appUser.value?.copy(authToken = token)
      }
    }
    e
    f
    i
    • 4
    • 6
  • v

    Vitali Plagov

    07/25/2022, 7:51 AM
    I have a base class and two child classes extending this parent class. Can I declare a return type of the method in the parent class so that it will return the type of the child class that is extending it?
    open class Parent {
      fun load() {
        return ... // don't know what to return here
      }
    }
    
    class ChildA : Parent () {
      fun methodA() = ...
    }
    
    class ChildB : Parent () {
      fun methodB() = ...
    }
    
    class Usage {
      fun fooA() {
        ChildA().load().methodA() // I want to achieve this chaining
      }
    
      fun fooA() {
        ChildB().load().methodB()
      }
    }
    d
    • 2
    • 2
  • m

    martmists

    07/25/2022, 10:54 AM
    Is there a better way to do function calls similar to this?
    someFunction(  // takes varargs
        *arrayOf(if (condition) "someValue" else null).filterNotNull().toTypedArray(),
    )
    w
    e
    +2
    • 5
    • 4
  • v

    Vampire

    07/25/2022, 11:43 AM
    For "reasons" we have in our Gradle build logic
    import org.gradle.api.Action
    
    inline fun <T> action(crossinline block: T.() -> Unit): Action<T> {
       return object : Action<T> {
          override fun execute(t: T) {
             t.run(block)
          }
       }
    }
    But updating Gradle to 7.5 and thus Kotlin to 1.6.10 now gives a compilation error (well warning, but we have
    -Werror
    ) about wrong nullability:
    w: ...\buildSrc\src\main\kotlin\...\util\SamHelper.kt: (10, 7): Override 'fun execute(t: T): Unit' has incorrect nullability in its signature comparing with overridden 'fun execute(p0: T): Unit'
    What is his problem suddenly and how do I mitigate it?
    s
    • 2
    • 3
  • z

    zain

    07/26/2022, 11:49 AM
    I have this data class in Stat, all properties have some default value.
    data class Stat(
        val bR: Int?  = 1,
        val cS: Int? = 2,
        val fP: Int? = 3,
        val gA: Int? = 4,
        val gC: Int? = 5,
        val gOB: Int? = 6,
        val gS: Int? = 7
    )
    How do I get all properties and their respective values of an object? val stat = Stat( ) stat.forEach { property, value } Is this possible in Kotlin?
    e
    j
    +4
    • 7
    • 9
  • d

    Dmitry Romanov [JB]

    07/26/2022, 2:08 PM
    Hey folks, If you are new to Kotlin, we recommend starting with the free Kotlin Basics track on JetBrains Academy. You’ll learn Kotlin by creating real-world applications and also benefit from: • A personalized study plan • Project-based learning • Immediate feedback • Integration with IntelliJ IDEA • A community of 500,000 learners
  • g

    Gavin Ray

    07/26/2022, 6:10 PM
    Which of these is likely to perform better? I assume the
    List
    version but you never know, figured I'd ask others:
    fun recur(...): Sequence<*> = sequence {
        yield(...)
        getQueryRelations(innerRequest).forEach {
            yieldAll(
                recur(...)
            )
        }
    }
    fun recur(...): List<*> {
        return listOf(...) + getQueryRelations(innerRequest).flatMap {
            recur(...)
        }
    }
    e
    • 2
    • 4
  • j

    Jason5lee

    07/27/2022, 7:43 AM
    I'm writing a DSL. It's something like this.
    class Scope {
        fun method(block: () -> Unit) {}
    }
    
    fun scope(block: Scope.() -> Unit) {}
    
    fun main() {
        scope {
            method {
                method {  } // I want to disallow using the scope inside the method
            }
        }
    }
    I want to disallow calling method on the
    Scope
    inside the
    method
    . I know I can have a dummy receive object and mark the
    Scope
    and the dummy object
    DslMarker
    .
    @DslMarker
    annotation class MyDslMarker
    
    @MyDslMarker
    class Scope {
        fun method(block: Context.() -> Unit) {}
    }
    
    @MyDslMarker
    object Context // Dummy object
    
    fun scope(block: Scope.() -> Unit) {}
    
    fun main() {
        scope {
            method {
                method {  } // Compiler error now
            }
        }
    }
    Any better solution?
    s
    • 2
    • 5
  • n

    Nat Strangerweather

    07/27/2022, 12:16 PM
    Hi, this piece of code works fine but it looks odd to me (all the exclamation marks!)... I suspect I am not making the best use of the Kotlin language. Could you please give me your opinion? If it can be done better, what would I need to work on?
    val skillRating = MutableLiveData(0)
        fun calculateSkillRating() {
            if (readWinCount.value != 0 && readLossCount.value != 0) {
                skillRating.value = averageWinningScore.value?.plus(
                    (400 * (readWinCount.value?.minus(readLossCount.value!!)!!) /
                            (readWinCount.value?.plus(readLossCount.value!!)!!))
                )
            }
        }
    j
    s
    d
    • 4
    • 9
  • j

    janvladimirmostert

    07/27/2022, 9:08 PM
    is there a difference between anonymous function
    val a = fun (): String {
       return ""
    }
    or 
    val a = fun () = ""
    and lambda expression
    val b: () -> String = {
       ""
    }
    or
    val b = { "" }
    in any way other than just the syntax?
    r
    d
    z
    • 4
    • 8
  • p

    phldavies

    07/28/2022, 10:59 PM
    Can anyone shed some light as to why the compiler is raising an “Overload resolution ambiguity” in the following?
    fun CtxA.action() = CtxA
    fun CtxC.action() = Unit
    
    context(CtxA, CtxB)
    fun bothContexts() {
        // Overload resolution ambiguity. All these functions match.
        // public fun CtxA.action(): CtxA defined in root package in file CtxRcv.kt
        // public fun CtxC.action(): Unit defined in root package in file CtxRcv.kt
        action()
    }
    
    context(CtxA)
    fun onlyCtxA() = action() // works fine
    As far as I can tell, it shouldn’t even be considering
    CtxC.action
    as a candidate as it’s not in scope. I can qualify as
    this@CtxA.action()
    but obviously not ideal.
    y
    • 2
    • 3
  • s

    sen

    07/29/2022, 3:13 AM
    Is there a way to change parameter names of extension functions? Say we have:
    fun SomeClass.someFunction(param: Int) {
        // Do something...
    }
    We would invoke it as
    SomeClass().someFunction(5)
    and in Java it would be
    KotlinClassKt.someFunction( /** this$SomeClass **/ SomeClass(), 5)
    So my question is, can I change the parameter of the function?
  • a

    Ayfri

    07/29/2022, 12:33 PM
    Hi, is there a First In First Out collection in Kotlin which we can set a limited size ?
    g
    a
    s
    • 4
    • 4
  • m

    Matt Yokan

    07/30/2022, 12:23 AM
    Meta question, does anyone know how to get invited to the JB Fleet discord?
    p
    • 2
    • 1
  • g

    Gavin Ray

    07/30/2022, 5:30 PM
    I've been writing a relational DB in Kotlin as a learning exercise, and I'd like to implement codegen for the expression evaluator (it's currently interpreted) In Scala you have
    quasiquotes
    , which let you quote Scala code to have it be evaluated as an AST + compiled instead of interpreted This makes codegen really easy compared to using something like Janino Does Kotlin have something similar? Maybe in the K2 internal API's or something? I didn't find anything on Google searching for
    kotlin codegen library
    =/
  • g

    Gavin Ray

    07/30/2022, 5:34 PM
    Essentially I want to implement the equivalent of this:
    def eval(e: Expression): AST = e match {
      case Literal(value) => q"$value"
      case Attribute(name) => q"row.get($name)"
      case Add(left, right) => q"${eval(left)} + ${eval(right)}"
    }
    i
    • 2
    • 5
  • j

    juh juh

    07/31/2022, 8:27 PM
    Is there a way to mark an interface method, so the IDE would show a warning when calling it, unless suppressed?
    m
    v
    j
    • 4
    • 4
  • e

    Eric Boggs

    07/31/2022, 10:36 PM
    Hello all - Any good suggestions on who to follow in the Kotlin community?
    r
    y
    • 3
    • 3
  • g

    Gleb Minaev

    08/01/2022, 4:13 PM
    Hi! Can someone tell me what is
    jvm-abi-gen
    compiler plugin that was mentioned in 1.7.20-Beta release notes? I can not find any documentation on it.
    d
    i
    • 3
    • 4
  • j

    juh juh

    08/01/2022, 8:26 PM
    Is there a way to create objects array without filling and manually fill it afterwards? Like, in my case I have something like this, but it's a bit ugly, and it does unnecessary filling array with
    null
    val tempLines = Array<IntArray?>(width + height) { null } as Array<IntArray>
                for (x in 0 until width) {
                    tempLines[x] = IntArray(height) { y -> x + y * width }
                }
                for (y in 0 until height) {
                    tempLines[y + width] = IntArray(width) { x -> x + y * width }
                }
    Creating two arrays and concatenating them via
    +
    is not an option, because performance is very critical
    k
    e
    • 3
    • 20
  • s

    sundernegi

    08/02/2022, 11:37 AM
    Hello Anyone can help me how to save MP3 file in android/data/package name/files directory
  • n

    Nat Strangerweather

    07/14/2022, 1:12 PM
    Hi, there is a problem with my code but I can't figure out what it is. Basically, when I select distinct characters, the fourth one onwards gets double its value. But say I select four Es (or four of any same character), the fourth E is not multiplied by 2.
    fun getWordValue() {
            val workingArray = repository.arr.distinct()
            val list = mutableListOf(0)
    
            word.value!!.forEach { c ->
                workingArray.forEach {
                    if (it.name.contains(c)) {
                        when (c) {
                            word.value!![0] -> list.add(it.value)
                            word.value!![1] -> list.add(it.value)
                            word.value!![2] -> list.add(it.value)
                            else -> list.add((it.value * 2))
                        }
                    }
                }
            }
            wordValue.value = list.sum()
            saveWordValue(wordValue.value!!)
        }
    I'd be grateful for some help, thanks!
    s
    j
    +2
    • 5
    • 25
Powered by Linen
Title
n

Nat Strangerweather

07/14/2022, 1:12 PM
Hi, there is a problem with my code but I can't figure out what it is. Basically, when I select distinct characters, the fourth one onwards gets double its value. But say I select four Es (or four of any same character), the fourth E is not multiplied by 2.
fun getWordValue() {
        val workingArray = repository.arr.distinct()
        val list = mutableListOf(0)

        word.value!!.forEach { c ->
            workingArray.forEach {
                if (it.name.contains(c)) {
                    when (c) {
                        word.value!![0] -> list.add(it.value)
                        word.value!![1] -> list.add(it.value)
                        word.value!![2] -> list.add(it.value)
                        else -> list.add((it.value * 2))
                    }
                }
            }
        }
        wordValue.value = list.sum()
        saveWordValue(wordValue.value!!)
    }
I'd be grateful for some help, thanks!
s

Sam

07/14/2022, 1:16 PM
This is a bit hard to understand because the code mentions a few things that are defined elsewhere. Can you simplify the example at all? Either that, or give some more info about what
repository
,
word
and
wordValue
are.
➕ 1
j

Joffrey

07/14/2022, 1:16 PM
What do you mean by select? It'd be nice to extract just the problematic piece of code for reproducibility. Here this function is entangled with many other global things that you read or write to (which by the way is a smell, given the name of the function).
@Sam you beat me to it 😄
s

Sam

07/14/2022, 1:17 PM
Just barely 😄
n

Nat Strangerweather

07/14/2022, 1:18 PM
Thanks, let me think 🙂
I have a list of scrabble letters which form my array in my repo. The reason I put
distinct
in my
workingArray
is that some of the scrabble letters are repeated several times. Each letter has a name and a value.
Then, the game requires that I make words that I check in a database to see if they exist. For each word, the first 3 letters have their own number of points. If the word is longer each subsequent letter has double the points.
Maybe my code is too clumsy. I'll try and sort something out.
This is in my ViewModel by the way.
s

Sam

07/14/2022, 1:32 PM
The first suggestion that comes to mind is to change
word.value!!.forEach { c ->
to
word.value!!.forEachIndexed { i, c ->
Where
i
will give you the position of the character in the word.
g

Giorgos Makris

07/14/2022, 1:48 PM
Given a character and its index in the word, can you find its value?
j

Joffrey

07/14/2022, 1:51 PM
Given a character and its index in the word, can you find its value?
Actually this would be easy if instead of converting the letters array by just using
distinct()
you used a
Map<Char, Int>
from letter to value:
val lettersToValues = repository.arr.associate { it.name to it.value }
n

Nat Strangerweather

07/14/2022, 2:19 PM
Sorry for the late reply; I went for a walk... Thank you, I'll try out your suggestions! 😊
n

Nolan

07/15/2022, 1:58 PM
I don't know if anyone answered the question of what the problem is with the existing code. The problem is that your
when
statement will always hit the first condition in the scenario you described because it's comparing the values. So if your word is "EXCEPT", the first "E" and the fourth "E" will match
word.value!![0]
because that evaluates to "E".
:thank-you: 1
n

Nat Strangerweather

07/15/2022, 8:23 PM
Thanks for this! I managed to make it work in the end by getting rid of the
when
statement in order to make my code less awkward, and using the suggestions that were made above. But it's good to know why this did not work in the first place. 😊 Here is what the code looks like now:
fun getWordValue() {
        val list = mutableListOf(0)
        val lettersToValues = repository.arr.associate { it.name to it.value }

        word.value!!.forEachIndexed() { i, c: Char ->
            if (i in 0..2) {
                list.add(lettersToValues.getValue(c.toString()))
            } else {
                list.add(lettersToValues.getValue(c.toString()) * 2)
            }
        }
        wordValue.value = list.sum()
        saveWordValue(wordValue.value!!)
    }
j

Joffrey

07/15/2022, 9:21 PM
Also, why do you add to a list if all you want is a sum? You could just increment a total instead
g

Giorgos Makris

07/15/2022, 10:30 PM
this seems like a great use case for fold, if you want to avoid the mutable list altogether
n

Nat Strangerweather

08/02/2022, 1:28 PM
Coming back to this, is there any plausible reason why from the tenth char onwards values stop being multiplied by 2?
fun getWordValue() {
        val lettersToValues = repository.arr.associate { it.name to it.value }
        word.value!!.forEachIndexed { i, c: Char ->
                if (i in 0..2) {
                    lettersToValues.getValue(c.toString())
                } else {
                   lettersToValues.getValue(c.toString()) * 2
                }
                wordValue.value = c.toString().sumOf { i }
            } 
    }
s

Sam

08/02/2022, 1:32 PM
I’m a little confused by your code here. You’re calling
lettersToValues.getValue(…)
but you don’t seem to do anything with the result. In an earlier version of your code you were adding it to a list, I think.
c.toString().sumOf { i }
also looks odd, and probably doesn’t do what you want it to.
n

Nat Strangerweather

08/02/2022, 1:33 PM
Yes, it's just that someone said it was useless to add it to a list
s

Sam

08/02/2022, 1:33 PM
To answer your question, though, I can’t see anything obvious that would make the code behave differently on/after the tenth loop iteration.
n

Nat Strangerweather

08/02/2022, 1:33 PM
but even adding it to a list causes the same issue
ok thanks, I need to look elsewhere in my code then 🙂
j

Joffrey

08/02/2022, 6:14 PM
When I said to not add to a list, I also mentioned incrementing a counter instead. Basically instead of adding all elements to a list and then going through the list to add them all, you could use a variable that keeps the total-so-far, and increment it. But you still need to use the value anyway. You could also use
fold
which is a functional way of doing it.
View count: 8