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

    ivano

    01/09/2020, 8:00 AM
    if (ocrItem.pattern is DateRegex) {
                            ocrItem.newValue = result.transformToDefaultDate()
                        } else {
                            ocrItem.newValue = result
                        }
    a
    m
    • 3
    • 5
  • j

    Jérôme Gully

    01/10/2020, 9:53 AM
    sealed class NotificationData(val contactDisplayName: String) {
        class Message(contactDisplayName: String, val contentMessage: String) : NotificationData(contactDisplayName)
        class Join(contactDisplayName: String) : NotificationData(contactDisplayName)
        class File(contactDisplayName: String) : NotificationData(contactDisplayName)
        class Audio(contactDisplayName: String) : NotificationData(contactDisplayName)
    }
    Is there a better way to initialize the
    contactDisplayName
    property ?
    contactDisplayName
    is defined in the base class and each child class "override" it
    m
    • 2
    • 2
  • c

    corneil

    01/10/2020, 7:47 PM
    I've updated the KFSM project documentation with an ImmutableFSM example. I would appreciate any feedback. The project site: https://open.jumpco.io/projects/kfsm Specific example: https://open.jumpco.io/projects/kfsm/index.html#immutable-context-example
    c
    • 2
    • 1
  • j

    Jérôme Gully

    01/14/2020, 2:50 PM
    open class ParticipantsExtension {
        companion object {
            const val ELEMENT = "participants"
        }
    
        open fun getElement() = ELEMENT
    
        fun parse() {
            // common code used with ELEMENT from child
        }
    }
    
    class UpdatedParticipantsExtension : ParticipantsExtension() {
        companion object {
            const val ELEMENT = "updated-participants"
        }
        override fun getElement() = ELEMENT
    }
    
    class AddedParticipantsExtension : ParticipantsExtension() {
        companion object {
            const val ELEMENT = "added-participants"
        }
        override fun getElement() = ELEMENT
    }
    IS there a better way with no redundant code ? I must access overridden
    ELEMENT
    as static fiel in an other class, AND use
    ELEMENT
    in the base function
    parse()
    with the overridden value
    g
    m
    +2
    • 5
    • 8
  • i

    ivano

    01/21/2020, 2:21 PM
    companion object {
            fun <T> fromData(data: T): Result<T> {
    
                return Result(data, null)
            }
    
            fun <T> fromError(error: Throwable): Result<T> {
    
                return when (error) {
                    is HttpException -> {
                        if (error.code() in 400..499) {
    
                            if (error.code() == 401) AccountStorage().signOut()
    
                            mapErrorBody(error, PAErrorModel::class.java)?.let {
                                return Result(null, it)
                            } ?: return Result(null, PAErrorModel("", error.localizedMessage))
                        }
    
                        return Result(null, PAErrorModel("", error.localizedMessage))
                    }
                    else -> Result(null, error)
                }
            }
        }
    m
    l
    • 3
    • 9
  • a

    arekolek

    01/24/2020, 8:30 AM
    // 1
    interface FooFactory {
        fun getFoo(): Foo
    }
    
    // 2
    interface FooFactory : () -> Foo
    
    // 3
    interface FooFactory : () -> Foo {
        override fun invoke(): Foo
    }
    Is 2 or 3 something that people do? (not using a
    typealias
    here, because it wouldn't work with Dagger)
    3️⃣ 1
    2️⃣ 1
    1️⃣ 4
    m
    m
    • 3
    • 3
  • p

    Paul Woitaschek

    01/25/2020, 3:44 PM
    @Georgi Naumov Sure: https://gist.github.com/PaulWoitaschek/617435b8b3180c31cc3fbf87b5dd06e7
    👍 3
    g
    • 2
    • 3
  • m

    myanmarking

    01/28/2020, 2:53 PM
    var date: LocalDateTime = from
    while (date.isBefore(LocalDateTime.now())) {
        getDataFromXXX(date = date)
        date = date.plusHours(1)
    }
    p
    • 2
    • 5
  • g

    Georgi Naumov

    01/29/2020, 8:38 AM
    I am stuck with Date assertion in different timezones. May someone give me a hint? https://gist.github.com/gonaumov/cc60cc8fafc74da937f8291a6efeda70
    k
    c
    m
    • 4
    • 10
  • t

    tipsy

    01/31/2020, 3:30 PM
    is there a nicer way of writing this?
    inputStream.apply { skip(from.toLong()) }.use {
        var bytesLeft = bytesToWrite
        while (bytesLeft != 0) {
            val read = it.read(buffer, 0, Math.min(buffer.size, bytesLeft))
            outputStream.write(buffer, 0, read)
            bytesLeft -= read
        }
    }
    m
    t
    • 3
    • 26
  • k

    Kashif

    02/03/2020, 4:06 PM
    what is the good way to writing this code:
    override fun getOrderInfoList(status: String, chainID: String, debugTag: String): Flowable<Result<List<OrderInfo>>> {
        logger.d(TAG, "Getting order list for status %s", status)
        val fetchFromStorageObservable = storageDataSource.getOrderList(debugTag)
        val observeStorageObservable = storageDataSource.observeOrderList(debugTag)
        // function which fetches from the local storage and takes a throwable that might be re-thrown if there's no data found locally
        val fetchFromStorageOrThrowObservable = fun (t : Throwable) : Observable<Result<List<OrderInfo>>> {
            fetchFromStorageObservable.map {
                if(it.isEmpty()) {
                    // re-throw the exception from the Remote source since we got no data from the Local source
                    throw t
                }
                it
            }
        }
        val fetchFromRemoteObservable = remoteDataSource.getOrderInfoList(status, chainID).toObservable().onErrorResumeNext { t: Throwable ->
            logger.d(TAG, "order list not received from server")
            // fallback to the local source
            fetchFromStorageOrThrowObservable(t)
        }.flatMap {
            if (it is Result.Success) {
                persisOrderInfoList(it.data)
            }
            fetchFromStorageObservable
        }
        return Observable.concat(fetchFromRemoteObservable, observeStorageObservable).toFlowable(BackpressureStrategy.LATEST)
    }
    k
    m
    • 3
    • 11
  • m

    Medamine Rihane

    02/07/2020, 12:59 PM
    @Kashif i think its better to always get data from local and update local data every time you have changes so you have a single source of data/truth
    k
    • 2
    • 1
  • d

    Daniel

    02/08/2020, 12:16 PM
    Might there be a better way to change a character in a string?
    fun String.setCharAt(index: Int, char: Char) = StringBuilder(this)
            .apply {
                setCharAt(index, char)
            }.toString()
    Googling franticly, but I can't find an inbuild method for this
    m
    k
    • 3
    • 7
  • a

    Alex Woods

    02/10/2020, 6:14 PM
    Hey guys, got 2 questions about default values and annotations. 1. Is there a way to get the default value of a parameter using reflection?
    data class Foo(val a: String = "hello")
    
    // can I access "hello" somehow, like Foo::class.fields.map { it.defaultValue }
    2. What’s the maximum supertype I can use on an annotation? I know annotations can only take certain values (primitives in Java, classes, etc.).
    @Target...
    annotation class Bar<T>(val value: T)   // nope!
    
    annotation class Bar(val value: Any)   // nope!
    Is there some supertype for anything that is valid in an annotation?
    b
    • 2
    • 2
  • e

    Ellen Spertus

    02/11/2020, 7:55 PM
    Could someone look over this code?
    private fun getIntent(utterance: String): Intent =
      IntentRunner.processUtterance(utterance)?.let { intent ->
        intent.resolveActivityInfo(packageManager, intent.flags)?.let { activityInfo ->
          if (activityInfo.exported) intent else null
        }
      } ?: Intent(
        Intent.ACTION_VIEW,
        Uri.parse("${BASE_URL}${URLEncoder.encode(utterance, ENCODING)}")
      )
    The idea is that I want the bottom
    Intent
    to be returned if either
    processUtterance()
    returns null,
    resolveActivityInfo()
    returns null, or
    activityInfo.exported
    is false. I welcome comments on correctness and style.
    t
    • 2
    • 3
  • d

    dfriehs

    02/13/2020, 1:43 PM
    I have caches that are built (and rebuilt) in full, but may take a bit of time during generation. I need all coroutines that access the cache to suspend until the cache is built. My current solution looks like this:
    class DelayUntilReady<T>(private val builder: () -> T) {
        private companion object {
            enum class State { READY, WAIT }
        }
    
        private val channel: Channel<Unit> = Channel(0)
        private var state: State = State.WAIT
    
        fun setReady() {
            state = State.READY
            channel.offer(Unit)
        }
    
        fun setWait() {
            state = State.WAIT
        }
    
        suspend fun get(): T {
            while (state == State.WAIT) channel.receive()
            return builder.invoke()
        }
    }
    
    
    object Cache {
        private var elements: Map<String, String> = emptyMap()
        private val elementAwait = DelayUntilReady { elements }
        
        @Suppress("FunctionName")
        suspend fun Elements(): Map<String, String> = elementAwait.get()
    
        fun setupElements(builder: () -> Map<String, String>) {
            elementAwait.setWait()
            // parse
            elements = builder.invoke()
    
            elementAwait.setReady()
        }
    }
    Did I miss something, or is there a better way to write this? Please note that i will have around 4-5 of these caches in the
    Cache
    object, not just one as in the example.
    z
    • 2
    • 3
  • a

    am

    02/18/2020, 7:18 AM
    Reposting it here https://kotlinlang.slack.com/archives/C0B8MA7FA/p1582007328306300
    d
    • 2
    • 1
  • d

    Diego Almeida de Oliveira

    02/19/2020, 8:12 PM
    Hey guys, which one of these approaches you think would be better in terms of performance, memory, etc?
    1
    class Foo {
    
    	private val logger: Logger by lazy { Logger(getApplicationContext()) } 
    
    	fun aFunctionCalledMultipleTimes() {
    		logger.doSomething()
    	}
    }
    2
    class Foo {
    
    	fun aFunctionCalledMultipleTimes() {
    		val logger = Logger(getApplicationContext())
    		logger.doSomething()
    	}
    }
    s
    d
    • 3
    • 3
  • e

    Ellen Spertus

    02/21/2020, 12:15 AM
    There must be a nicer way to do this…
    private fun createSearchIntent(mr: MatcherResult) = 
        mr.slots[THING_KEY]?.let { thing ->
            val suffix = mr.slots[LOCATION_KEY]?.let { "in $it" } ?: ""
                Intent(
                     Intent.ACTION_VIEW,
                     Uri.parse("navigation:q=$thing$suffix")
                 )
        }
    c
    • 2
    • 2
  • d

    dave08

    02/24/2020, 6:15 PM
    What's the preferred way to declare an alternative result in Kotlin:
    // 1
    data class SomeResult(val typeOne: Bundle? = null, val orTypeTwo: Intent? = null)
    
    if (typeOne == null) 
       doSomething(typeTwo)
    else
       doSomething(typeOne!!)
    or:
    // 2
    sealed class SomeResult {
        class TypeOneWrapper(val result: Bundle) : SomeResult
    
        class TypeTwoWrapper(val result: Intent) : SomeResult
    }
    
    when (result) {
      is TypeOneWrapper -> doSomething(result)
      is TypeTwoWrapper -> doSomething(result)
    }
    The second seems cleaner, but requires funny ...Wrapper and val names (since the result type is not owned by me...), but the first is not as robust (doesn't ensure that at least one is set...).
    2️⃣ 2
    z
    k
    j
    • 4
    • 9
  • b

    Brendan Weinstein

    02/24/2020, 10:11 PM
    What's a good word for something that is close to being the real thing without being the real thing? The context is naming an android build variant for internal customers that will be signed with the release keystore, have the same package name as the production release, and have a debug tools menu available. This build would exist for testing things like google play billing, single sign-on within a suite of company apps, and 3rd party oauth.
    d
    g
    +4
    • 7
    • 13
  • c

    Can Orhan

    02/26/2020, 2:17 PM
    There’s been some code produced that’s created mixed feelings in the team. I’d love to hear your feedback on it. This class was created to give meaning to why a value would be missing within a model
    sealed class UserInput<out T : Any> {
        data class Value<T : Any>(val output: T) : UserInput<T>()
        object Missing : UserInput<Nothing>()
    }
    The problem with it is that we can’t use Kotlin’s null-safe operators like
    :?
    and
    .?
    . Do you think there is value in knowing why something is missing? If so, is it worth the loss of null-safe operators?
    m
    z
    • 3
    • 10
  • t

    tipsy

    03/09/2020, 2:47 PM
    is there are a better way than this for getting key by value?
    val key = myMap.filterValues { it == "value" }.keys.firstOrNull()
    a
    • 2
    • 2
  • e

    Ellen Spertus

    03/09/2020, 5:38 PM
    Is there a better way of writing this?
    internal fun getString(key: String): String? {
        val (tableName, fieldName) = splitDottedString(key)
        return getString(tableName, fieldName)
    }
    • 1
    • 1
  • e

    Ellen Spertus

    03/24/2020, 12:15 AM
    Is there a better way of writing this:
    override fun toString() =
            StringBuilder("MatchResult(\"").apply {
                append(baseString())
                append("\"")
                append(slotString())
                append(if (parameters.isEmpty()) "" else ", parameters: $parameters")
                append(if (skippedWords == 0) "" else ", skippedWords: $skippedWords")
                append(if (aliasedWords == 0) "" else ", aliasedWords: $aliasedWords")
                append(intentName?.let { ", intentName: $it" } ?: "")
                append(", capturedWords: $capturedWords)")
            }.toString()
    a
    m
    e
    • 4
    • 10
  • m

    miqbaldc

    03/24/2020, 11:27 AM
    anyone knows why the lambda listener for
    setOnClickLIstener
    doesn’t works on point 1, but works in point 2,
    DebouncingOnClickListener
    is an interface that override
    View.OnClickListener#onClick(View)
    to prevent spamming click see this code below:
    // 1. this doesn't works
    fun View.setDebouncingOnClickListener(onSafeClick: (View) -> Unit) {
        setOnClickListener(DebouncingOnClickListener {
            onSafeClick(it)
        })
    }
    
    // 2. this works
    fun View.setDebouncingOnClickListener(onSafeClick: (View) -> Unit) {
        val listener = DebouncingOnClickListener {
            onSafeClick(it)
        }
        setOnClickListener(listener)
    }
    a
    • 2
    • 6
  • d

    Daniel

    03/25/2020, 10:15 PM
    Hmhm, struggling to find a good name for a extension function that returns true when two lists have identical content (same references).
    fun <T> List<T>.isSameAs(other: List<T>): Boolean {
            if(size != other.size) return false
    
            forEachIndexed { index, element ->
                if(element !== other[index]) return false
            }
    
            return true
        }
    Does anybody have an idea? Also maybe there might be a better way to check this?
    s
    b
    m
    • 4
    • 9
  • c

    Cody Engel

    04/03/2020, 2:30 PM
    sealed class Article {
        abstract val title: String
        abstract val body: String
        abstract val updatedAt: Date
        abstract val categories: List<Category>
    
        data class New(
            override val title: String,
            override val body: String,
            override val updatedAt: Date,
            override val categories: List<Category>
        ) : Article()
    
        data class Existing(
            override val title: String,
            override val body: String,
            override val updatedAt: Date,
            override val categories: List<Category>,
            val id: UUID
        ) : Article()
    }
    👋🏻 I’m working on modeling the different states an object could be in (say for
    GET
    ,
    POST
    ,
    PUT
    , and
    DELETE
    ) and I’ve landed on this for now. The
    New
    variant would be exclusively for
    POST
    requests while the
    Existing
    would be used for
    GET
    ,
    PUT
    , and
    DELETE
    , although the delete would only require the id. Thoughts?
    j
    • 2
    • 3
  • z

    zmunm

    04/06/2020, 5:45 AM
    Is there simple function of this?
    list.lastOrNull { it is Goods } as? Goods
    p
    • 2
    • 3
  • e

    Eugen Martynov

    04/09/2020, 9:18 AM
    Is it idiomatic kotlin?
    val check = true
    
    when(check) {
        true -> println("it's true")
        false -> println("it's false")
    }
    m
    c
    d
    • 4
    • 4
Powered by Linen
Title
e

Eugen Martynov

04/09/2020, 9:18 AM
Is it idiomatic kotlin?
val check = true

when(check) {
    true -> println("it's true")
    false -> println("it's false")
}
m

Mike

04/09/2020, 11:53 AM
For a boolean,
if
is the more readable choice.
When
is better for completeness check on enum/sealed class, or those cases where your
if
has at least 3 branches.
e

Eugen Martynov

04/09/2020, 12:55 PM
That was my assumptions, but is it common sence or written somewhere?
c

Cody Engel

04/09/2020, 1:41 PM
I don't know if it's been written down anywhere but it's implied. One advantage of the language is being concise, using the when is not as concise as say...
if (check) println("it's true") else println("it's false")
d

daphillips

04/09/2020, 2:40 PM
Kotlin's coding conventions mention it: https://kotlinlang.org/docs/reference/coding-conventions.html#if-versus-when
👍 3
View count: 3