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

    bod

    06/12/2021, 9:28 AM
    Hello, World! Hey, an interop question: how would you return a
    Future<Void>
    in a Kotlin library (so it's nice for Java users)? I'd like to avoid returning
    Future<Unit>
    because this would expose a Kotlin specific type to my API.
    e
    • 2
    • 3
  • x

    Xy Ren

    06/12/2021, 10:21 AM
    Hi there, I was trying to match the types of two values simultaneously. I realized it was not doable with
    when
    . Is there any library dealing with this kind of problem or any idiomatic way? I tried to roll a dsl but it looked terrible:
    c
    • 2
    • 2
  • t

    Tianyu Zhu

    06/12/2021, 6:32 PM
    I'm having some trouble with type inference. For example, if I write:
    val myMap = mapOf("id" to 10, "hash" to 99999L)
    I would expect the
    id
    key to contain an
    Int
    and the
    hash
    key to contain a
    Long
    , but that's not the case--
    id
    is now mapped to a long! I can fix this by writing
    val myMap = mapOf("id" to 10 as Int, "hash" to 9999L)
    But then IntelliJ tells me that the cast is not needed. Is there a better way?
    h
    e
    • 3
    • 8
  • t

    Toby

    06/12/2021, 11:06 PM
    Is there a nice way of accessing functions and/or variables (members in general) of a class without initializing it? I think it would be some kind of a singleton but I've only seen very complex approaches. Should be like an object but it's indeed a class.
    r
    e
    +3
    • 6
    • 12
  • e

    E.Kisaragi

    06/13/2021, 8:50 AM
    quick question: is coroutine in experimental?
    🇳🇴 2
    b
    c
    • 3
    • 2
  • d

    Daniel

    06/13/2021, 7:43 PM
    When I followed the IDE auto-suggestion to rename
    10.seconds
    to
    Duration.seconds(10)
    I got an error that
    Duration.seconds
    does not exist. Autocomplete shows the only members of
    Duration.Companion
    are
    ZERO
    and
    INFINITY
    . However, jumping to the definition of
    Duration
    shows
    fun seconds
    . I don't understand what could cause this
    e
    • 2
    • 4
  • t

    Tim McCormack

    06/14/2021, 12:18 AM
    Can someone take a look at my build config and see if there's some obvious way to speed up compilation and testing? https://gitlab.com/timmc/cavern/-/blob/master/spelunk/pom.xml Right now it takes about a minute and a half to do
    mvn test -Dtest="StateTest"
    . I don't have the fastest computer, but I feel like this should take 30 seconds at most. Alternatively, is there some way I can do incremental compilation and/or testing? Anything to get the feedback loop down to seconds rather than minutes.
    v
    • 2
    • 8
  • m

    Marcin Wisniowski

    06/14/2021, 9:52 AM
    What is the official logo of Kotlin? I see both :kotlinnew: and :kotlin: in various places. The official website uses :kotlinnew:, but the Press Kit contains only :kotlin:. Are they both in active use? What is the difference?
    :kotlinnew: 9
    m
    n
    +3
    • 6
    • 10
  • d

    David Smith

    06/14/2021, 11:00 AM
    oh, I just realised the code above is fine, the reason is that my code uses a function, not just the value
    sealed class Parent() {
        data class Child(val value: String) : Parent()
    }
    data class Other(val value: (Parent) -> String)
    val child = Child("something")
    val f: (Child) -> String = { child -> child.value}
    val x = Other(f as (Parent) -> String)
    :thread-please: 3
    d
    • 2
    • 9
  • s

    Slackbot

    06/14/2021, 12:25 PM
    This message was deleted.
    n
    n
    • 3
    • 3
  • j

    Jérémy CROS

    06/14/2021, 1:23 PM
    Hello guys 🙂 Was looking to simplify a bit of code I have Looks like this :
    sealed class Sealed(open val x: Int) {
        data class A(override val x: Int) : Sealed(x)
        data class B(override val x: Int) : Sealed(x)
    }
    
    private fun copyTest(test: Sealed, y: Int): Sealed {
        // "standard" way, it works
        return when (test) {
            is Sealed.A -> test.copy(x = y)
            is Sealed.B -> test.copy(x = y)
        }
        // Sadly, this does not
        return test.copy(x = y)
    }
    Is the when approach the only one? Or am I missing something? Thanks!
    l
    • 2
    • 2
  • a

    Arjan van Wieringen

    06/14/2021, 2:17 PM
    Hi all, a high level question. I am test driving Elm and like it. However, it got me thinking of something Kotlin related. If I was to create some sort of VDOM consisting of simple data classes and compare those that would just work fine. However, when I'd include events, using some sort of 'onClick' anonymous function, the diffing will always cause to assert that the anonymous functions are different, even when they are structurally the same. As I believe Elm doesn't have this problem (because of a complete different language and compiler). Example:
    data class Node(val name: String, val onClick: () -> Unit)
    
    fun main() {
        val a = Node("Foo") { println("Foo") }
        val b = Node("Foo") { println("Foo") }
        println(a == b) // prints "false"
    }
    Is there a way to obtain something similar?
    a
    y
    p
    • 4
    • 6
  • r

    Ruckus

    06/14/2021, 4:59 PM
    I'm trying to find a way to bring multiple values into scope with inheritance. Currently this is what I'm doing:
    interface A {
        val prop1: ...
        val prop2: ...
        ...
    
        companion object : A {
            ...
        }
    }
    
    interface B : A {
        val prop3: ...
        ...
    
        companion object : B, A by A {
            ...
        }
    }
    Is there a way to do this without the weird interface / companion construct?
    h
    e
    s
    • 4
    • 20
  • p

    Patrick Ramsey

    06/14/2021, 11:22 PM
    I continue to struggle with finding a good, go-to pattern for error types in kotlin 😕 Say you have a hardware device, and you want to present a bunch of data about that device. Its serial number, its battery state, etc. Each one of these data requires issuing a command to the device and reading a response, and that command might fail. These values all have different types --- some are counters, some are strings, some are dates, etc. But they all have exactly the same failure semantics --- the device might return an error. Say, further, that all of these data accessors are defined on top of an underlying sendCommand function, which always returns a string or error. From the caller’s perspective, the fact that these methods are defined in terms of sendCommand() is an implementation detail — they expect to be informed of how the device access failed (which is to say, the set of errors returned by the lower-level sendCommand is exactly the same as the set of errors returned by these field accessors by definition). Is the best possible pattern in this scenario to define a generic Result<T> type, and for every single field accessor, to write, e.g.,
    when (sendCommand(val result = command)) {
        is Result.Success<CommandResponse> -> Result.Success(getDerivedValue(result))
        is Result.SomeFailure<CommandResponse> -> Result.SomeFailure(result.message)
        is Result.OtherFailure<CommandResponse> -> Result.OtherFailure(result.message)
    }
    I can’t think of a better way, but this feels incredibly boilerplatey — I’d love to be able to just return the underlying errors (since that’s what the caller will care about), but that doesn’t work since the generic type parameter is changing (even though the error subtypes don’t actually make use of the type parameter). Alternatively, I could just hide the error, and present these fields as properties that are null if the lookup failed. But then I’ve robbed the caller of the ability to respond meaningfully to the failure. TL;DR: is there any good pattern for forwarding a lower-level error up the call stack, where appropriate? Because I can certainly think of cases where that seems very appropriate.
    j
    n
    e
    • 4
    • 137
  • p

    Pablo

    06/15/2021, 10:42 AM
    Is there any kotlinian way to avoid an if else after a
    find
    or
    firstOfNull
    ?
    val foo = bar.firstOfNull {whatever}
    if(foo==null) smthing()
    else smthing2()
    e
    v
    +4
    • 7
    • 9
  • k

    Kingsley Izundu

    06/15/2021, 1:22 PM
    Hello Kotlinians its good to be here, i hope to learn and collaborate as much and share with the community as well. I just finished from an Interview for the role of Android Engineering... wish me luck please.
    m
    • 2
    • 2
  • m

    MrNiamh

    06/15/2021, 1:38 PM
    Is there a way to sum multiple fields of a data class into a new instance? E.g.
    private data class Quantity(val quantity: BigDecimal, val pendingQuantity: BigDecimal)
    fun main(){
        val quantities = listOf(Quantity(BigDecimal.ONE, BigDecimal.ZERO), Quantity(BigDecimal.ZERO, BigDecimal.TEN), Quantity(BigDecimal.ONE, BigDecimal.ONE))
        println(quantities.sum()) //expecting Quantity(2, 11)
    }
    Obviously
    .sum()
    doesn’t work, just an example of what i’d like it to look like
    d
    h
    • 3
    • 3
  • d

    Danish Ansari

    06/15/2021, 1:40 PM
    What is the easiest way to get value from
    Map<String,String>
    with case insensitive
    String
    key? More context and detailed scenario in the thread...
    a
    s
    +2
    • 5
    • 11
  • k

    kevindmoore

    06/15/2021, 4:22 PM
    Is it ever ok to use runBlocking in regular code? Somehow that seems wrong
    e
    c
    g
    • 4
    • 8
  • y

    y9san9

    06/15/2021, 8:25 PM
    Is there any multiplatform library for strings localization? I mean something like:
    object Strings : LocalizedStrings {
        val hello by string(default = "Hello") {
            val ru by value("Привет")
            val ua by value("Прівіт")
        }
    }
    
    fun main() {
        Strings.locale = "ru"  // This should be also built in library with different realizations on each platform
        println(Strings.hello)
    }
    Also would be nice to provide mutable state for compose, observable value for kvision, etc.
    t
    • 2
    • 3
  • p

    Patrick Ramsey

    06/16/2021, 1:25 AM
    So… what are the rules for when a (non-suspending) inline function can be used to call suspending code? .let(), for instance, works in both blocking and asynchronous contexts (ie, the lambda passed to .let() can call suspend functions if .let() was called from a coroutine body). However, it seems like if any restrictions are put on the lambda’s return type at all, suddenly it becomes necessary to declare your function as a
    suspend inline
    function (ie,
    inline fun <T> foo(() -> T) {}
    works in a suspend context;
    inline fun foo(() -> Int) {}
    does not). Am I correct about that? And if so, out of curiosity, what’s the implementation reason?
    e
    • 2
    • 4
  • a

    althaf

    06/16/2021, 3:19 AM
    Hey, .. Is there neater way to do this
    fun foo() : Response {
                 workFlowLog?.let {  Response.Sucess(BatchApprovalWorkFlowList(workFlowLog) ) } ?: run { Response.Error(Exception()) } 
    }
    My intention is to return different response in case workflow is null. My team mates say this kinda of ugly. Is there a better kotlin idiom to craft this statement. if( w == null) ... else ... , we are trying to avoid this.
    e
    r
    d
    • 4
    • 13
  • m

    Mark

    06/16/2021, 6:06 AM
    Which do you prefer for removing all occurrences of a specific hard-coded character?
    1. someString.replace(" ", "")
    2. someString.filterNot { it == ' ' }
    3. someString.filterNot(' '::equals)
    1️⃣ 13
    r
    r
    • 3
    • 3
  • m

    missguru

    06/16/2021, 3:50 PM
    Hey folks, I took the liberty to start a channel for jobs worldwide who offer relocation and remote options. #jobsworldwide Feel free to join! 🙂
    a
    b
    • 3
    • 3
  • d

    David Smith

    06/16/2021, 4:31 PM
    does anyone know of an optics library for kotlin that works with jackson
    JsonNode
    ?
    :google: 1
    j
    • 2
    • 2
  • e

    E.Kisaragi

    06/16/2021, 7:50 PM
    are GitHub language-color and the new logo related?
    :kotlinnew: 1
    b
    • 2
    • 1
  • l

    LastExceed

    06/17/2021, 9:30 AM
    why does the former work but not the latter ?
    Untitled.cpp
    d
    g
    • 3
    • 2
  • o

    Orhan Tozan

    06/17/2021, 10:11 AM
    Are namespaces coming to Kotlin? Really missing that feature for organizing top level functions. As an alternative there are `object`s, but a function inside an object isn't enforced to be stateless..
    c
    r
    +2
    • 5
    • 10
  • d

    David Smith

    06/17/2021, 1:37 PM
    is there a nicer way of writing this in kotlin:
    val NullableData? = firstNullable?.let { first ->
                secondNullable?.let { second ->
                    NullableData(first, second)
                }
            }
    I have something like that but with many more fields so it is massively nested. I suppose I could turn nulls into exceptions and surround the whole thing in a try catch? In Haskell/Purescript/Scala we would have
    do
    notation for this and I think arrow had done something like this but I couldn’t find it?
    j
    n
    +3
    • 6
    • 39
  • l

    li'lfluf

    06/17/2021, 10:44 PM
    hello. i have an (external) library class that crashes in some rare circumstances. so i want to override one method and yolo suppress the exception. the method is not public though. it seems that i can override it if i make a new file with the package of that class (
    package library.package
    ). is there a reason i shouldn't do this?
    c
    l
    e
    • 4
    • 6
Powered by Linen
Title
l

li'lfluf

06/17/2021, 10:44 PM
hello. i have an (external) library class that crashes in some rare circumstances. so i want to override one method and yolo suppress the exception. the method is not public though. it seems that i can override it if i make a new file with the package of that class (
package library.package
). is there a reason i shouldn't do this?
c

crummy

06/17/2021, 10:51 PM
perhaps this is a use case for reflection?
l

louiscad

06/17/2021, 11:07 PM
If you have a way to inject the instance where the override is missing (including with reflection), yes, you can have a wrapper using
Proxy
from Java reflection to handle the missing override and delegate for the other ones.
l

li'lfluf

06/17/2021, 11:24 PM
i don't quite see why would I want to use reflection instead of simply having a class in a “fake” library package?
l

louiscad

06/17/2021, 11:28 PM
If you don't need reflection, don't use it, for sure
e

ephemient

06/18/2021, 12:12 AM
personally I've written quite a few bytecode transforms to fix up external libraries. can be done with Gradle (https://docs.gradle.org/current/userguide/artifact_transforms.html) or Android's build system (https://developer.android.com/reference/tools/gradle-api/7.1/com/android/build/api/transform/Transform)
although if you're on the desktop JVM and not Android, you could also perform the fixup in -javaagent (which is how I unit test my aforementioned transforms)
View count: 1