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

    arve

    07/31/2020, 12:49 PM
    Is there a consise way to skip an assignment if a value is null? e.g.
    // fun src.loadString(fieldName: String): String? {...}
    
    
    dstBuilder.fieldA = src.loadString("aField") ?: throw Exeption("Field A is not present") 
    // Instead of throwing, i want to leave dst.fieldA unset - skip this line and move to next.
    :thread-please: 1
    j
    t
    +6
    • 9
    • 17
  • n

    Nikolay Puliaev

    07/31/2020, 5:10 PM
    Hello. What function can find the difference between collections of objects by ID? Example:
    val list1 = listOf(ExampleObject(id = 1), ExampleObject(id = 2))
    val list2 = listOf(ExampleObject(id = 2))
    
    Result: listOf(ExampleObject(1))
    Thanks in advance.
    a
    b
    • 3
    • 5
  • s

    Sam Garfinkel

    07/31/2020, 8:46 PM
    Looking for advice on this: I am ingesting a sequence of chars, I want to buffer them until I receive a particular xml end tag then flush the buffer. Is there a more efficient (while also easy) way to check for the existence of this tag at the end of the buffer? I think the trivial method is
    endswith("</endtag>")
    but this seems inefficient to run over the length of the buffer, especially if we get a char that can’t contribute to the terminal tag.
    n
    n
    j
    • 4
    • 7
  • j

    Ju

    08/01/2020, 2:54 AM
    I have a question which is burning inside of my head recently... I've been doing a algorithm study with my friend. Till now we gather algorithm questions each other from internet and solve'em together every week. Gathering Q's every week is a bit painful and more hard to find them as the time goes by... what is a effective & efficient way to organize this gruop? any help?
    j
    m
    • 3
    • 3
  • j

    Ju

    08/01/2020, 4:04 AM
    What I'm looking for is what is the best way to organize the group... without gathering & picking tons of questions every week...
    m
    • 2
    • 8
  • m

    Mati Galli

    08/01/2020, 7:46 PM
    class OptionGroupControllerTest : KoinTest {
    
        private val optionGroup: String = this::class.java
                .getResource("/jsons/option_group.json")
                .readText()
                .replace("\n", "")
                .replace(" ", "")
    
        @BeforeTest
        fun setup() {
            startKoin {
                module {
                    single<OptionGroupController>()
                    single<OptionGroupService>()
                }
            }
        }
    
        @AfterTest
        fun teardown() {
            stopKoin()
        }
    
    
    
        @Test
        fun `create option`() = withTestApplication(Application::routes) {
            with(handleRequest(<http://HttpMethod.Post|HttpMethod.Post>, "/optionGroup") {
                addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString())
                setBody(optionGroup)
            }) {
                assertEquals(HttpStatusCode.Created, response.status())
            }
        }
    
    }
    My Routes:
    fun Application.routes() {
    
        val controllerOptionGroup: OptionGroupController by inject()
        val controllerOption: OptionController by inject()
    
        routing {
    
            get("/") {
                call.respondText("OK")
            }
    
            get("/health") {
                call.respondText("OK")
            }
    
            route("/optionGroup") {
                post {
                    try {
                        val message = call.receive<String>()
                        val messageOptionGroup: OptionGroupDTO = Mapper.read(message)
                        println("SERVER: Message from the client: $message")
                        call.respond(controllerOptionGroup.create(call, messageOptionGroup))
                    } catch (ex: ItemException) {
                        call.respond(HttpStatusCode.BadRequest, mapOf("code" to ex.code, "messages" to arrayListOf(ex.message)))
                    }
                }
            }
        }
    }
    And the exception is thrown at line:
    call.respond(controllerOptionGroup.create(call, messageOptionGroup))
    This problem only gives me when running the tests. When I run the application everything works correctly. I would really appreciate if someone can give me a hand with this 🙂
    n
    • 2
    • 7
  • k

    kqr

    08/02/2020, 7:10 AM
    hello. please what would be the most elegant way to solve this. I have inputString representing datetime. I have list of DateTimeFormatters of supported formats. How would I parse it? each parsing attempt throws exception. at the end I would like to either throw exception or return default value if none of the formatters succeed. thx
    b
    z
    +2
    • 5
    • 32
  • b

    Big Chungus

    08/02/2020, 10:29 AM
    Where do I get started with making a contribution to stdlib-common and making it available for ALL platforms?
    i
    a
    • 3
    • 5
  • h

    Hullaballoonatic

    08/02/2020, 10:59 PM
    Is it possible to get the instance of the companion object of an inheriting class?
    s
    a
    • 3
    • 5
  • j

    jenji

    08/03/2020, 4:50 PM
    Hey Kotlin folks - I’ve got a kotlin design challenge, looking for some ideas. I’m building a library that supports java & kotlin teams. The core is naturally Kotlin, but needs to be extensible by both Java & Kotlin. The only real hangup I’ve got is that some of the parts that need to be extended are part of the concurrency model, and I’m using coroutines to get that sweet sweet structured concurrency. Coroutines & java don’t seem to play very nice together. I’m not even talking suspend functions here, just trying to go between java & kotlin or vice versa, aside from the easy translation of completable futures. Anyway, the specific issue: I’ve got some behavior components that are plug able, and may need to do some async tasks. I provide them with a facade to interact with other parts of the system, which seems like a natural place to bridge between coroutines & traditional threading. However, I’m not seeing a way to go from a standard java threading model to coroutines. A coroutine wrapper for Runnable/Callable is trivial though. Thoughts?
    s
    b
    o
    • 4
    • 13
  • m

    Matteo Mirk

    08/04/2020, 8:24 AM
    Do you people know of any equivalent of ArchUnit for Kotlin? I couldn’t find one. The closest I found is this detekt plugin which checks a few design principles but it’s not the same thing.
    k
    w
    • 3
    • 10
  • m

    Mehdi Haghgoo

    08/04/2020, 4:26 PM
    Hi. The date for some kotlin articles is too old, March 1 1972 😂. Not sure if it is a site issue or Google indexing issue.
    😀 7
    i
    a
    +3
    • 6
    • 8
  • b

    bbaldino

    08/04/2020, 11:52 PM
    I'm running into a strange issue: lib A is a mixed kotlin+java project. I'm trying to use lib A from lib B, and all extension functions/free functions in lib A are unable to be found from kotlin in lib B. I am able to see them from java code in lib B. Is there something weird where the kotlin versions get clobbered?
    d
    • 2
    • 8
  • t

    Tomas Kartasovas

    08/05/2020, 2:42 PM
    Hi, is there a way to use static c library in kotlin mutliplatfom project?
    b
    • 2
    • 1
  • p

    poohbar

    08/05/2020, 4:58 PM
    anybody came across this?
    # JRE version: Java(TM) SE Runtime Environment (8.0_261-b12) (build 1.8.0_261-b12)
    # Java VM: Java HotSpot(TM) 64-Bit Server VM (25.261-b12 mixed mode bsd-amd64 compressed oops)
    # Problematic frame:
    # J 29740 C2 kotlin.reflect.jvm.internal.impl.descriptors.runtime.structure.ReflectClassUtilKt.getDesc(Ljava/lang/Class;)Ljava/lang/String; (73 bytes) @ 0x000000011803a082 [0x0000000118039e20+0x262]
    a
    • 2
    • 1
  • i

    ilyagulya

    08/06/2020, 9:33 AM
    Hello, guys! I'm getting a compiler crash when I'm using the kotlinx.serialization. Can you help me please and tell how can I make kotlin compiler more verbose to find where is the issue and file a bug (or event maybe a pull request to kotlin)? This does not work:
    kotlinOptions {
        verbose = true
    }
    a
    • 2
    • 4
  • o

    Ola Denslaw

    08/06/2020, 10:50 AM
    Hello 👋  Is anyone here looking for a full-time position as a Mobile Engineering Manager? I am working with a fun and very successful social media/dating app, who are looking for Android Manager to act as a support partner to the Director of Mobile, essentially taking some pressure from the team and allowing the product teams ideas come to life and helping engineers to thrive in their roles.  They are a diverse team who value communication & feedback, so they are looking for someone likeminded to lead their Android function.   They are all about work-life balance, it’s full remote until April 1st at least, you will get every second Friday off and flexible working through the year.  The company is offering up to $200k as a base salary, plus a healthy bonus, equity, unlimited holidays and many more fantastic benefits. They are on a mission to create a digital world which will allow singles to connect, rather than just swipe right or left.  If you like the sound of this role, please get in touch 🙂
    a
    • 2
    • 1
  • z

    zkeme

    08/06/2020, 1:27 PM
    Hi guys! Does anyone know if there is a better way to do this so that I don't have to do explicitly casting?
    fun <T : Any> getFoo(defaultValue: T): Foo<T> {
    
        return when (defaultValue) {
            is Long -> LongFoo(defaultValue) as Foo<T> //LongFoo extends Foo<Long>
            is Int -> IntFoo(defaultValue) as Foo<T> //IntFoo extends Foo<Int>
            is String -> StringFoo(defaultValue) as Foo<T> //StringFoo extends Foo<String>
            else -> NonPrimitiveFoo(defaultValue, defaultValue.javaClass)
        }
    }
    s
    n
    • 3
    • 6
  • l

    Luis Munoz

    08/06/2020, 3:35 PM
    Is it terrible to connect to an external service in the constructor? i.e...
    init {
            factory = ConnectionFactory().apply {
                setUri(config_uri)
                // Attempt recovery every 5 seconds
                isAutomaticRecoveryEnabled = true
            }
            rabbitConnection = factory.newConnection()
    n
    s
    n
    • 4
    • 14
  • e

    eddMX

    08/06/2020, 5:52 PM
    Hi, regards from Mexico
    👋 4
    l
    • 2
    • 1
  • s

    Sam Garfinkel

    08/06/2020, 6:37 PM
    Is there any operator for Iterables that allows you to map with some mutable state, then push that state to the next iteration? Sort of like a reduce but only to map not to flatten. I suppose I could
    fold
    with a mutable list of
    Pairs
    .
    n
    p
    • 3
    • 4
  • v

    viralshah

    08/06/2020, 6:37 PM
    Is there a recommended library for SQL generation in Kotlin, preferably with an example? I don’t necessarily want an ORM but just type safety and composability
    d
    r
    • 3
    • 4
  • k

    Kyaw Za Zaw

    08/06/2020, 7:44 PM
    If anyone uses JaCoCo in CI pipelines (especially Azure), how has your experience been?
    b
    • 2
    • 1
  • a

    Allan Wang

    08/06/2020, 10:00 PM
    Does kotlin have an elegant equivalent to
    chunked
    , where the partial window is at the start? eg with list
    [1, 2, 3, 4, 5, 6, 7, 8]
    ,
    chunked
    gives
    [[1, 2, 3], [4, 5, 6], [7, 8]]
    , but I want
    [[1, 2], [3, 4, 5], [6, 7, 8]]
    . Or do I have to modulo myself and chunk when I know it's a multiple of my chunk window?
    i
    n
    • 3
    • 10
  • m

    Matthew Pope

    08/07/2020, 1:54 AM
    just curious—anyone have a use case for using
    Nothing?
    in your code anywhere?
    z
    n
    +4
    • 7
    • 18
  • t

    TwoClocks

    08/07/2020, 6:02 AM
    Anyone used KSP over KAPT yet? Does it do multi pass? I have a some kapt annotations that get their types from other annotation processing and the kapt stub's don't compile (ironically the rest of the project does after all the annotation processors run).
    m
    d
    • 3
    • 5
  • k

    Kris-Gerhard Aabrams

    08/07/2020, 6:46 AM
    I'm using a Kotlin specific library. Everything works in JVM mode but when running the app as native somewhy this check fails. https://github.com/sksamuel/hoplite/blob/master/hoplite-core/src/main/kotlin/com/sksamuel/hoplite/decoder/DecoderRegistry.kt#L44
    l
    s
    • 3
    • 49
  • a

    Alf_

    08/07/2020, 12:37 PM
    Hey guys, Can I do something like this with when expresion?
    val arrayNumber = arrayOf(0, 1, 2, 3)
    
    if (arrayNumber.contains(0)) {
        //DO SOMETHING FOR CASE 0
    }
    
    if (arrayNumber.contains(1)) {
        //DO SOMETHING FOR CASE 1
    }
    
    if (arrayNumber.contains(2)) {
        //DO SOMETHING FOR CASE 2
    }
    
    if (arrayNumber.contains(3)) {
        //DO SOMETHING FOR CASE 3
    }
    Thanks in advance!
    s
    p
    +2
    • 5
    • 9
  • t

    TwoClocks

    08/07/2020, 7:52 PM
    kapt $ annotation processing : How exactly do you make one that's incremental? All the docs say "it's supported now" but none of them mention now to make one.
    e
    • 2
    • 2
  • f

    Flazzarino

    08/08/2020, 12:36 PM
    👋 hi, is it possible to suspend a suspend function then continue/resume it more than once?
    d
    e
    +2
    • 5
    • 8
Powered by Linen
Title
f

Flazzarino

08/08/2020, 12:36 PM
👋 hi, is it possible to suspend a suspend function then continue/resume it more than once?
d

darkmoon_uk

08/08/2020, 1:24 PM
Can you give us a use case? The simple answer is probably 'yes' - for example, try putting
delay(<someDuration>)
into your suspending method more than once - that will result in it being suspended multiple times.
f

Flazzarino

08/08/2020, 1:39 PM
Sorry, I believe I meant coroutine. Say I have a suspend function that prints a string once. Is it possible to make a coroutine context that would print it twice, given a single application?
d

darkmoon_uk

08/08/2020, 1:52 PM
Seems possible e.g. by making a custom dispatcher that dispatched twice; but it sounds like it could get hacky and 'abusive' - why not just call your suspend function twice?
f

Flazzarino

08/08/2020, 1:53 PM
I’m curious about effect handling. Wondering if kotlin can accommodate it.
e

ephemient

08/08/2020, 4:07 PM
it seems totally unsafe to allow it, and I'm pretty sure it won't work anyway: https://github.com/JetBrains/kotlin/blob/0c13a7f89a166015fcc281da745a5fc0719f73c4/libraries/stdlib/jvm/src/kotlin/coroutines/SafeContinuationJvm.kt#L45
else -> throw IllegalStateException("Already resumed")
s

streetsofboston

08/08/2020, 4:50 PM
You may want to look into
Flow
that has the same structured concurrency as suspend funs but can emit more than one value.
i

iseki

08/09/2020, 12:21 PM
What's the scene you faced? Looks it's a big abused usecase.
If you only want a try. Maybe you need to modify the internal state of the state machines. 😋
View count: 4