https://kotlinlang.org logo
Docs
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
  • a

    amit

    04/11/2020, 2:05 PM
    my assumption was that the lambda in getOrElse should need to return Heros object as default value
    s
    15 replies · 2 participants
  • b

    bjonnh

    04/15/2020, 7:28 PM
    Can I make an interface with variable types? interface IProcessor { fun <A> process(f: (A)-> Unit): ProcessorStatus }
    ✔️ 1
    s
    5 replies · 2 participants
  • a

    Alanna

    04/28/2020, 9:21 PM
    I'm calling assertEquals on two lists in a test case, but unfortunately i've run into the issue that list equality calls
    .equals()
    instead of
    ==
    , the two of which give me a different results.
    >>> 0f == -0f
    res0: kotlin.Boolean = true
    >>> 0f.equals(-0f)
    res0: kotlin.Boolean = false
    >>> listOf(0f) == listOf(-0f)
    res1: kotlin.Boolean = false
    The best way I've come up with to solve this is by defining my own assertEquals function that works on List<Float>, but this doesn't seem very clean to me. Is there a better way to do this? Also, why doesn't list equality use
    ==
    ?
    m
    s
    +2
    29 replies · 5 participants
  • a

    Aslam Hossin

    05/05/2020, 4:54 AM
    Listener registration not working in fragment to Dialog fragment communication. Am I missing anything for registration ?
    override fun onAttach(context: Context) {
        AndroidSupportInjection.inject(this)
        super.onAttach(context)
        if (context is Listener) {
          listener = context
        }
      }
    
      override fun onDetach() {
        super.onDetach()
        listener = null
      }
    d
    1 reply · 2 participants
  • e

    elect

    05/19/2020, 1:02 PM
    how may I extract the
    return
    (short and elegantly)?
    fun getArgCount(): Int {
            when (lastToken) {
                null -> return 1
                is Token.OpenParentheses, is Token.ArgumentSeparator -> {
                    return 1
                }
                else -> (lastToken as? Token.Operator)?.operator?.let { lastOp ->
                    if (lastOp.numOperands == 2 || lastOp.numOperands == 1 && !lastOp.isLeftAssociative)
                        return 1
                }
            }
            return 2
        }
    k
    2 replies · 2 participants
  • t

    Tuang

    05/22/2020, 9:46 AM
    hi guys, i needs some review for my code.
    fun A(infoA: Info, conn: Connection, userId: Int): Result {
            val overSettingOfA: OverSetting = AppSetting.instance.retrieveA(infoA, conn, userId)
            // some code
            return Result(overSettingOfA)
        }
    
    
    
        fun B(infoB: Info, conn: Connection, userId: Int, someInfo: SomeInfo): Result {
            val overSettingOfB: OverSetting = AppSetting.instance.retrieveB(infoB, userId, conn, someInfo)
            // some code
            return Result(overSettingOfB)
        }
    Both of 
    fun A
     and 
    fun B
     have the same logic, what they are doing is all the same. I m trying to do likes high order function but the problem is the argument is not the same, 
    fun A
     has 3 arg and 
    fun B
     has 4. Is there any a magical way? 😀
    m
    b
    12 replies · 3 participants
  • j

    JP

    05/24/2020, 10:51 AM
    Hello, I am a beginner in Kotlin and in general statically typed language. I wanted to practice the OOP concepts using Kotlin, so I wrote some code for implementing singly linked list (one mutable and one immutable) as Kotlin’s Collection, referencing some codes from Kotlin’s source code. I’m yet not so confident with how I structure the code using interfaces and classes, so I’d like to get some comments. Thanks a lot in advance. An exemplary question that arose was: should I have used abstract class in between? (I am not yet sure what the differences between interfaces and abstract classes are, and when to use which.)
    SinglyLinkedLists_kt.kt
    k
    6 replies · 2 participants
  • e

    Eugen Martynov

    05/28/2020, 9:25 AM
    Do you prefer
    abstract class A {
      abstract fun doSomething()
    }
    with
    object: A() {
      override fun doSomething(){}
    }
    or
    class A(private val doSomething: () -> Unit)
    with
    A() {...}
    ?
    a
    m
    4 replies · 3 participants
  • v

    vaskir

    06/19/2020, 12:29 PM
    @LastExceed
    val last = (0..3).flatMap { x ->
        (0..3).map { y ->
            offsets.sumBy { (first, second) ->
                arr[y + second][x + first]
            }
        }
    }.max()
    l
    1 reply · 2 participants
  • a

    arekolek

    06/25/2020, 2:26 PM
    For filtering true booleans: 1️⃣
    .filter { it }
    or 2️⃣
    .filter(true::equals)
    2️⃣ 3
    1️⃣ 18
    p
    2 replies · 2 participants
  • a

    andyg

    06/28/2020, 8:18 PM
    I'm trying to update a property of a class in place, but the updates are having no effect unless I do it via re-assignment. I know there is a better way but I'm failing to find it...
    data class counters(var small: Int, var big: Double)
    fun Int.add3() : Int = this + 3   // accepts Int, returns Int
    fun Double.times2pt5() : Double = this * 2.5 
    
    fun main() {
        val mycounters : counters = counters(4, 201.0)
        mycounters.small.apply{ this.add3() }
        mycounters.apply { this.big.times2pt5() }
        println(mycounters) // prints 4, 201.0 -- same as original
        
        val uglyCounters : counters = counters(6, 401.0)
        uglyCounters.apply {
            this.small = this.small.add3()
            this.big = this.big.times2pt5()
        }
        println(uglyCounters) // works, prints 9, 1002.5, but is ugly
    }
    j
    11 replies · 2 participants
  • j

    Jakekudur

    07/02/2020, 4:39 AM
    how can I optimize this piece of code?
    g
    5 replies · 2 participants
  • p

    Philipp Mayer

    07/08/2020, 10:11 AM
    Is there a more functional approach to this? I don't really like creating a new variable just to check if it is empty. Thanks guys!
    val newSmth = listOfObjects.filter { ... }
            if (newSmth.isNotEmpty()) {
                otherWorkflow.process(newSmth)
            }
    j
    a
    +2
    7 replies · 5 participants
  • e

    Eugen Martynov

    07/15/2020, 6:46 PM
    Hi people, I'm not sure about how to satisfy compiler. I wrote next code
    class DebounceClickListener(val clickListener:View.OnClickListener): View.OnClickListener{}
    z
    6 replies · 2 participants
  • a

    Afzal Najam

    08/13/2020, 3:56 AM
    Wrote a list/table syncing function in idiomatic Kotlin and without. I find the non-idiomatic one more readable right now. Would love to hear a better way to write it. Both pass my unit tests. https://gist.github.com/AfzalivE/48a9e225246c5cee144b06695f68731a
    g
    a
    17 replies · 3 participants
  • e

    Eugen Martynov

    08/24/2020, 9:45 AM
    Do you prefer people to use
    filterNot
    or
    filter { not condition }
    . I missed
    Not
    in the
    filterNot
    recently in review. It is probably matter of time when I will be fine.
    t
    m
    +1
    6 replies · 4 participants
  • m

    Mark

    08/30/2020, 2:33 AM
    Is there a better way to do this?
    class FlowDelegate<T>: ReadWriteProperty<Any, Flow<T>> {
        private val deferredFlow = CompletableDeferred<Flow<T>>()
    
        override fun setValue(thisRef: Any, property: KProperty<*>, value: Flow<T>) {
            deferredFlow.complete(value)
        }
    
        override fun getValue(thisRef: Any, property: KProperty<*>): Flow<T> {
            return if (deferredFlow.isCompleted) {
                deferredFlow.getCompleted()
            } else {
                flow {
                    emitAll(deferredFlow.await())
                }
            }
        }
    }
    
    /** Usage */
    class MySample {
        private var _sampleFlow by FlowDelegate<String>()
    
        val sampleFlow: Flow<String>
            get() = _sampleFlow
    
        fun init(args: ...) {
            _sampleFlow = flow<String> { /* based on args */ }
        }
    }
    z
    m
    10 replies · 3 participants
  • k

    KV

    09/21/2020, 4:56 AM
    Hello , how to write this function is best way ?
    fun String?.trimTrailingZeros(): String? {
        if (isNullOrEmpty() || this!!.indexOf(".") < 0) return this
        return replace("0*$".toRegex(), "").replace("\\.$".toRegex(), "")
    }
    e
    m
    +2
    13 replies · 5 participants
  • d

    delblanco

    10/21/2020, 10:37 AM
    Is there a collection function to pair one element with all others from the same list? For example: given
    listOf(A,B,C)
    I would like to end up with the following pairs:
    A to B, A to C, B to C
    Currently I got something like this but it feels non-idiomatic and inefficient...
    val users = listOf(User("A"), User("B"), User("C"))
    	val chats = users.flatMap{ u1 ->
            users.filterNot { u1 == it }
                .map { u2 -> Chat(setOf(u1, u2)) }
        }.toSet() // filters out duplicates
    b
    4 replies · 2 participants
  • c

    christophsturm

    10/24/2020, 11:10 AM
    in a api like this:
    data class User(
        val name: String,
        val birthday: LocalDate
    )
    Find<User>().where(User::name.like("blah%").and(User::birthday.between(date1, date2)))
    can i somehow change it to make it possible to remove the
    User::
    part and rewrite it like
    Find<User>().where(::name.like("blah%").and(::birthday.between(date1, date2)))e
    z
    2 replies · 2 participants
  • m

    Mark

    11/03/2020, 1:38 AM
    I’ve got a
    Sequence
    of `String`s and apply lots of mapping operations. Now, after these mappings I want to access the original index in the sequence. However, if I use
    mapIndexedValue
    then I need to change each mapping operation implementation. Instead, is it recommended to declare and use something like this (not tested) so that we can continue to use the same transforms as before? Side note: is there a danger in using mutable values like this?
    data class IndexedMutableValue<T>(val index: Int, var value: T)
    
    fun <T> Sequence<T>.withIndexedMutableValue(): Sequence<IndexedMutableValue<T>> =
        mapIndexed { index, t -> 
            IndexedMutableValue(index, t)
        }
    
    fun <T> Sequence<IndexedMutableValue<T>>.mapIndexedMutable(transform: (T) -> T): Sequence<IndexedMutableValue<T>> {
        forEach { it.value = transform(it.value) }
        return this
    }
    
    fun <T> Sequence<IndexedMutableValue<T>>.mapIndexedMutableNotNull(transform: (T) -> T?): Sequence<IndexedMutableValue<T>> {
        forEach { it.value = transform(it.value) ?: return@forEach }
        return this
    }
    
    fun <T> Sequence<IndexedMutableValue<T>>.flatMapIndexedMutable(transform: (T) -> Sequence<T>): Sequence<IndexedMutableValue<T>> {
        return sequence {
            forEach { indexedValue ->
                transform(indexedValue.value).forEach { newValue ->
                    yield(indexedValue.copy(value = newValue))
                }
            }
        }
    }
    e
    4 replies · 2 participants
  • j

    jean

    11/13/2020, 7:44 AM
    Any better way than this to transform a string to a map?
    private fun cookieStringToMap(string: String): Map<String, String> {
        val map = mutableMapOf<String, String>()
        string.split(";").forEach { entry ->
            val parts = entry.split("=")
            map[parts[0]] = parts[1]
        }
            
        return map
    }
    b
    l
    +3
    6 replies · 6 participants
  • c

    christophsturm

    11/24/2020, 3:35 PM
    is there a simpler way to write this:
    return if (value != null)
                (value as Number).toDouble()
            else
                null
    (not
    (value as? Number).toDouble()
    , which acts differently)
    w
    j
    +1
    10 replies · 4 participants
  • l

    LastExceed

    12/16/2020, 12:49 PM
    I gave https://adventofcode.com/2020/day/11 a try and this is my solution. It works, but i'm not happy with it. any ideas how to improve the readability ? or is functional style bound to be unreadable ?
    Untitled
    j
    1 reply · 2 participants
  • j

    Joris PZ

    12/20/2020, 7:57 AM
    I am playing around with different ways of defining a factory function to map a scalar to an enum. For instance:
    enum class OpCode(val code: Int) {
        QUERY(0), IQUERY(1), STATUS(2), NOTIFY(4), UPDATE(5), UNSUPPORTED(-1);
    }
    
    fun Int.toOpCode(): OpCode {
        return OpCode.values().find { it.code == this } ?: OpCode.UNSUPPORTED.also {
            log.error { "Unsupported DNS OpCode $this" }
        }
    }
    This uses a receiver function, which I like in general, and obviously there are many different ways of writing this function (such as
    fun toOpcode(code:Int): Opcode
    ) etc. Now, it occurred to me that this is also possible:
    enum class OpCode(val code: Int) {
        QUERY(0), IQUERY(1), STATUS(2), NOTIFY(4), UPDATE(5), UNSUPPORTED(-1);
    
        companion object {
            operator fun invoke(code: Int): OpCode {
                return values().find { it.code == code } ?: UNSUPPORTED.also {
                    log.error { "Unsupported DNS OpCode $this" }
                }
            }
        }
    }
    This allows the caller to map an
    Int
    to an
    OpCode
    using what looks like a constructor:
    val code = OpCode(0)
    What would you say if you saw this in a pull request? Is this clever and nice, or horrible and confusing and just showing off? I keep switching sides myself... 🙂
    m
    m
    +1
    10 replies · 4 participants
  • m

    Mark

    12/30/2020, 12:11 PM
    I’m surprised there is not something for this in the standard lib. Is this okay or maybe remove inline/reified?
    inline fun <reified K, V> Map<out K?, V>.filterKeyNotNull(): Map<K, V> =
        mapNotNull { (key, value) -> if (key != null) key to value else null }.toMap()
    m
    i
    3 replies · 3 participants
  • j

    jean

    01/07/2021, 8:31 AM
    I have this (ugly) code that works :
    lifecycleScope.launch {
        viewModel.state.collect { updateState(it, binding) }
    }
    lifecycleScope.launch {
        viewModel.load()
    }
    I cannot have
    viewModel.load()
    inside the first block after
    collect
    since it never ends and if I put it before I miss a bunch of events. Is there a way to write this in a better way?
    g
    3 replies · 2 participants
  • m

    Milan Hruban

    01/07/2021, 11:31 AM
    When using slf4j (or other) loggers, do you use 1️⃣ string interpolation -
    <http://logger.info|logger.info>("the value is $value")
    2️⃣ passing additional arguments -
    <http://logger.info|logger.info>("the value is {}", value)
    3️⃣ :thread-please: something else?
    2️⃣ 5
    a
    m
    +3
    8 replies · 6 participants
  • a

    alex cole

    01/10/2021, 1:36 AM
    What name should I use instead of
    toNumber()
    for the following code to follow the kotlin style guide.
    class ArrayND {
        var data: ArrayList<Double> = {...}
        var shape: Array<Int> = {...}
    
        operator fun get(vararg indicies: Int): ArrayND {...}
    
        fun toNumber(): Double {
            if (data.size == 1) {
                return data[0]
            } else {
                Throw Error
            }
        }
    }
    ✅ 1
    e
    2 replies · 2 participants
  • p

    Paulo Pinheiro

    01/13/2021, 11:34 AM
    I am not sure if this is a thing to ask feedback on open source pull requests. But if someone has free time we would love to get some feedback on https://github.com/google/flatbuffers/pull/6387
    p
    2 replies · 2 participants
Powered by Linen
Title
p

Paulo Pinheiro

01/13/2021, 11:34 AM
I am not sure if this is a thing to ask feedback on open source pull requests. But if someone has free time we would love to get some feedback on https://github.com/google/flatbuffers/pull/6387
p

Paul Woitaschek

01/15/2021, 3:05 PM
There are kotlinx.benchmark annotations for org.openjdk.jmh.annotations.Benchmark That way you should be able to move the benchmark to commonMain
p

Paulo Pinheiro

01/18/2021, 9:46 AM
Thanks! I will look into that
View count: 2