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

    jdiaz

    06/27/2020, 1:54 PM
    Is the
    toString
    method of data classes deterministric? Or the order of fields isn't guaranteed?
    i
    4 replies · 2 participants
  • l

    leo_mendez

    06/27/2020, 3:01 PM
    Hello friends, I have been working on creating shortcut images for Kotlin Collections, these are the first ones. Feedback is always welcome.
    👍 1
    e
    2 replies · 2 participants
  • s

    Slackbot

    06/27/2020, 4:48 PM
    This message was deleted.
    s
    b
    2 replies · 3 participants
  • a

    andylamax

    06/28/2020, 9:54 AM
    How do I add javafx dependency as a gradle dependency? I am having a problem with CI/CD in github actions. In my pc, I can build and test my code coz I have the javafx runtime. However in the testing vm, it appears to be missing. Help please . . .
    d
    14 replies · 2 participants
  • p

    Phani Mahesh

    06/28/2020, 11:51 AM
    type safe classes representing updates.
    h
    1 reply · 2 participants
  • i

    Ifvwm

    06/28/2020, 2:12 PM
    interface IS<T> {fun <T>T.fmap():T}
    sealed class IIS<T>: IS<T>
    data class IntIS<Int>(val x:Int): IIS<Int>(){
        fun Int.fmap(){
            return x+1
        }
    }
    d
    k
    15 replies · 3 participants
  • g

    Gopal S Akshintala

    06/28/2020, 3:50 PM
    How to install Kotlin-1.4-M2 on command line, so that
    kotlinc -version
    shows
    kotlinc-jvm 1.4-M2
    ?
    d
    7 replies · 2 participants
  • k

    kenkousen

    06/28/2020, 7:53 PM
    When is it worthwhile to add a generic extension function to an existing class? For example, I often use Google's Gson to deserialize JSON data, and since Gson is a Java library, I have
    Gson().fromJson(json, MyDataClass::class.java)
    and I realize I could write
    inline fun <reified T> Gson.fromJson(json: String): T = this.fromJson(json, T::class.java)
    That way I can reduce the above expression to
    Gson().fromJson<MyDataClass>(json)
    My question is, is it worth doing that? Do I really gain anything? What do you think?
    j
    a
    5 replies · 3 participants
  • j

    Joakim Tengstrand

    06/29/2020, 8:15 AM
    Hi. Is it possible to store configuration in a separate file, e.g. config.yaml, and then read it from build.gradle.kts and then for example add data from the file in some sections in build.gradle.kts, e.g. the list of srcDirs? I use gradle dsl (I saw an example in gradle https://stackoverflow.com/questions/48318114/how-to-load-yml-propery-to-gradle but I don't know how to convert to gradle dsl):
    sourceSets.main {
        withConvention(org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet::class) {
            // Put components and bases here (src)
            kotlin.srcDirs(
                    "kotlin/bases/cli/src",
                    "kotlin/components/file/src",
                    "kotlin/components/srcreader/src"
            )
        }
    }
    h
    2 replies · 2 participants
  • m

    manlan

    06/29/2020, 9:09 AM
    If I have a list of objects with one of their properties being type, how do I split them into sub groups such that they are bundled by their type property while also retaining the order?
    Untitled
    s
    t
    +2
    12 replies · 5 participants
  • w

    william

    06/29/2020, 2:36 PM
    what would be the best way to calculate
    someComputationUsingA(a)
    while still being able to pass it to the super constructor and being able to access it in
    FooSubType
    class FooSubType(
        val a: Int,
        val b: String
    ): FizzSuperType(
        someComputationUsingA(a) + " $b"
    )
    In the above its only passed along and I can't access the original result of the computation. I'm a little unsure about how to retain it in
    FooSubType
    to access at a later time
    d
    m
    8 replies · 3 participants
  • c

    Constantin Muraru

    06/29/2020, 2:54 PM
    hey folKs. we have a cute little situation. how can we restart a Coroutine when an exception is thrown, given that we use a SupervisorJob? Below is an example, with a producer/consumer sharing a Channel. When the consumer receives an exception, it dies (gracefully), and nobody consumes messages anymore. Any tips on how we could fix this, so that messages can be consumed when exception is encountered? Appreciate any help.
    fun main() {
        val sender = Sender(GlobalScope.coroutineContext)
        GlobalScope.launch {
            sender.send("Message1") // this is processed
            sender.send("Message2") // this is not processed anymore :(
        }
        Thread.sleep(2000)
    }
    
    class Sender(
        coroutineContext: CoroutineContext
    ) {
    
        private val channel = Channel<String>(32768)
        private val supervisor = SupervisorJob(coroutineContext[Job])
        private val scope = CoroutineScope(coroutineContext + supervisor)
    
        init {
    
            val handler = CoroutineExceptionHandler { _, e ->
                println(e.message)
            }
    
            with(scope) {
                launch(handler) {
                    MyProcessor(channel).run() // <--- how can we restart/recreate it when exception is thrown?
                }
            }
        }
    
        suspend fun send(message: String) {
            channel.send(message)
        }
    }
    
    class MyProcessor(
        private val channel: Channel<String>
    ) {
    
        suspend fun run() {
            for (message in channel) {
                process(message)
            }
        }
    
        private suspend fun process(message: String) {
            // something that occasionally throws Exception
            println("Processing $message")
            throw RuntimeException("Failed to process $message")
        }
    }
    e
    3 replies · 2 participants
  • h

    hooliooo

    06/29/2020, 2:56 PM
    Hi guys, I’m currently working on a microservice where I must use a combinatorial algorithm for my application, I’m using an algorithm that tackles the combination sum II programming problem: Here is my implementation (copied from the internet):
    /**
         * Given a collection of integers and a target integer (target),
         * find all unique combinations of integers where the sums of the combinations equal the target.
         * @param integers The integers used in the combinations
         * @param target The target sum
         * @return List<List<Int>> which represents all the possible combinations of integers that sum up to the target
         */
        private fun combinationSumII(integers: IntArray, target: Int, limit: Int): List<List<Int>> {
            fun backtrack(
                integers: IntArray,
                target: Int,
                limit: Int,
                index: Int,
                trace: List<Int>,
                allCombinations: MutableList<List<Int>>
            ) {
                for (i in index until integers.size) {
                    val current = integers[i]
                    if (i > index && current == integers[i - 1]) continue
                    if (trace.size >= limit) break
    
                    val remainingValue = target - current
                    when {
                        (remainingValue == 0) -> {
                            val set = ArrayList<Int>(trace)
                            set.add(current)
                            allCombinations.add(set)
                        }
                        (remainingValue > 0) -> {
                            val newTrace = ArrayList<Int>(trace)
                            newTrace.add(current)
                            backtrack(integers, remainingValue, limit, i + 1, newTrace, allCombinations)
                        }
                    }
                }
            }
    
            val allCombinations = mutableListOf<List<Int>>()
            val result = mutableListOf<Int>()
            integers.sort()
            backtrack(
                integers = integers,
                target = target,
                limit = limit,
                index = 0,
                trace = result,
                allCombinations = allCombinations
            )
            return allCombinations
        }
    For small sets of data this will suffice but there are edge cases integers is a big array, and target is a bigger int. Is there anyway to make this more efficient? I need this algorithm to be as fast as possible. Test data with long computation time: Scenario 1
    val integers = 43..166.toList().toIntArray()
    val target = 600
    val limit = 5
    Scenario 2
    val integers = (22..166).toList().toIntArray()
    val target = 554
    val limit = 5
    References: Problem: https://leetcode.com/problems/combination-sum-ii/ Algorithm: https://github.com/topwu/leetkotlin/blob/master/src/main/kotlin/leetcode/CombinationSumII.kt
    m
    l
    +1
    8 replies · 4 participants
  • i

    Ifvwm

    06/30/2020, 1:31 AM
    how to do type constraints in kotlin? like I would like a value x only could have Int or String type?
    a
    m
    2 replies · 3 participants
  • u

    user

    06/30/2020, 9:30 AM
    message has been deleted
    a
    h
    +1
    4 replies · 3 participants
  • b

    bod

    06/30/2020, 11:33 AM
    Hello, World! I've faced this little issue a few times, and not sure what the "elegant" solution is. I have a non nullable
    val
    which is initialized in
    init
    , but the super's
    init
    calls a method that accesses it (so: before it's initialized). In that method I can do a
    if (myVar != null) { ...
    which works. But now I get a
    Unnecessary safe call on a non-null receiver
    warning 🙂 The compiler tells me this null check is useless since this val is non nullable... But here it can be
    null
    . I can of course ignore / suppress the warning but I was wondering if there's a deeper truth to this 🙂 Ideas?
    a
    l
    +1
    22 replies · 4 participants
  • d

    Davide Giuseppe Farella

    06/30/2020, 1:49 PM
    Hello, I have
    infix fun A.function(b): X
    , then I have
    operator fun X.invoke(f: () -> Unit)
    so I’m trying to call
    a function b { ... }
    But I get B cannot get invoked as a function, I’ve tried to use
    plus
    a function b +{ ... }
    But I got something similar. If it use infix
    infix operator fun X.invoke(f: () -> Unit)
    is fine (
    a function b invoke { ... }
    ), but cannot get rid of that explicit
    invoke
    If I do like
    (a function b) { ... }
    is also fine, but still ugly 🙂 Any solution? Thanks 🙂
    r
    s
    12 replies · 3 participants
  • w

    Wesley Acheson

    06/30/2020, 2:56 PM
    Is this the correct approach I've got multiple nullable properties and I'm trying to convert them to a
    Map<ContactDetailsType, ContactDetails>
    val email =  source.customer.customerEmail?.let { Customer.ContactDetailsType.EMAIL to Customer.EmailAddress(it)}
    val phone = source.customer.telephone?.let { Customer.ContactDetailsType.GENERAL_PHONE to it.toPhoneNumber() }
    val mobile = source.cardholderInfo?.mobilePhone?.let { Customer.ContactDetailsType.MOBILE to it.toPhoneNumber()}
    val landLine = source.cardholderInfo?.homePhone?.let { Customer.ContactDetailsType.MOBILE to it.toPhoneNumber()}
    
    val contactDetails: Map<Customer.ContactDetailsType, Customer.ContactDetails> = listOf(email, phone, mobile, landLine).filterNotNull().toMap()
    The only reason to convert to a list is filteringNotNull() which I get a warning that is useless in a collection anyway.
    a
    m
    +1
    5 replies · 4 participants
  • h

    Hadi Tok

    06/30/2020, 6:15 PM
    I have a jvm project has Kotlin/Java interop. At my kotlin data classes for calling some of the properties I get ’“java.lang.NoSuchMethodError” for getter and setter methods at runtime. I am doing the calls from kotlin. when I use JvmName annotation the issue is resolved for this field. Do anyone have an idea what could be wrong?
    z
    1 reply · 2 participants
  • a

    Ahmed Mourad

    06/30/2020, 7:28 PM
    Just released NoCopy, a Kotlin compiler plugin that enables using data classes as value-based classes by moderating usage of their
    copy
    method. https://github.com/AhmedMourad0/no-copy
    🎉 3
    ➕ 1
    j
    w
    5 replies · 3 participants
  • a

    andylamax

    07/01/2020, 12:05 AM
    How do I reduce the number of kotlin-daemons or gradle-daemon's in my machine? They take all 16GB that I have. And when I check. I might find something like two kotlin daemons and three gradle daemons.
    z
    l
    +1
    9 replies · 4 participants
  • s

    Steve Ramage

    07/01/2020, 4:52 AM
    Hrm, just learning and this is puzzling me:
    val moduleCache : java.util.Map<ModuleInfo, WeakReference<ModuleInfo>> = Collections.synchronizedMap(WeakHashMap<ModuleInfo, WeakReference<ModuleInfo>>())
    [TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH] Type inference failed. Expected type mismatch: 
    required:
    java.util.Map<ModuleInfo, WeakReference<ModuleInfo>>
    found:
    (MutableMap<ModuleInfo!, WeakReference<ModuleInfo>!>..kotlin.collections.Map<ModuleInfo!, WeakReference<ModuleInfo>!>?)
    q
    n
    +1
    16 replies · 4 participants
  • l

    louiscad

    07/01/2020, 8:15 AM
    How would you assert an array (or a list) is sorted by a given selector/property its elements have? My use case is enforcing the order of an enum based on one of its properties (its only property actually). EDIT: found a solution:
    enum ThatEnum(val thatProperty: Float) {
        FirstEntry(thatProperty = 10),
        AnotherEntry(thatProperty = 20),
        LastEntry(thatProperty = Float.POSITIVE_INFINITY);
    
        companion object {
            init {
                check(values().contentEquals(values().apply { sortBy { it.thatProperty } }))
            }
        }
    }
    That requires to
    companion object
    to be accessed for the check to execute, which is fine in my case since I use it to get instances of the enum early.
    a
    p
    +1
    6 replies · 4 participants
  • j

    jeggy

    07/01/2020, 4:06 PM
    I'm getting this error:
    Caused by: org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException: Argument 2: expected R, but found I
    along side a bunch of bytecode. Does anyone know how to read this and how I can figure out what's actually going wrong?
    a
    s
    13 replies · 3 participants
  • s

    Shabinder Singh

    07/02/2020, 7:37 AM
    I want to create Empty Mutable Sets from a list of Strings as their name , for Example-
    var countryList= mutableSetOf<String>()
    I want to somehow create empty sets as following -
    var us= mutableSetOf<String>()
    var in= mutableSetOf<String>()
    var br= mutableSetOf<String>()
    but i get elements in countryList set dynamically from internet , so how do i create empty sets named as above dynamically? us, in br are fetched from internet and added to countryList set dynamically.
    n
    d
    +1
    25 replies · 4 participants
  • l

    LastExceed

    07/02/2020, 9:36 AM
    what's the difference between a function and a val storing a lambda ? why do we need both ?
    s
    s
    +2
    17 replies · 5 participants
  • m

    Marc Knaup

    07/02/2020, 1:06 PM
    Is there something like
    SuspendCloseable
    ? 🤔 I have to delete a temporary file in
    close()
    but don’t want it to be a blocking call.
    z
    8 replies · 2 participants
  • o

    oscarg798

    07/02/2020, 3:06 PM
    hello I do not know if this is intended to work this way but I’m merging two flows and then collecting the result flow and catching the exceptions on it, but I just found that if one of the flows has an exception then the merge does not emit the value of the other flow nor the emitted value in the catch clause like:
    val flow1 = flow<Int> {
        emit(1)
    }
    val flow2 = flow<Int> {
        throw IOException()
    }
    merge(flow1, flow2).onEach {
        print(it.toString() + "\n")
    }.catch {
        emit(3)
    }.launchIn(CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>))
    Do I have to catch the flows before merging them or there is something wrong in the example ?
    z
    4 replies · 2 participants
  • x

    xii

    07/02/2020, 9:49 PM
    hey! is there an elegant way to do this?: I want a data class that takes a value, but if the value is null, have that value be the result of an operation on other two values. Example in thread
    k
    i
    4 replies · 3 participants
  • c

    crummy

    07/03/2020, 3:59 AM
    I've got a JVM project where I define an interface, now I'm creating a kotlin JS project where I'd like to implement the interface. But IntelliJ doesn't seem to resolve the dependency. Do dependencies of a Kotlin JS project have to be JS dependencies too?
    h
    m
    +1
    4 replies · 4 participants
Powered by Linen
Title
c

crummy

07/03/2020, 3:59 AM
I've got a JVM project where I define an interface, now I'm creating a kotlin JS project where I'd like to implement the interface. But IntelliJ doesn't seem to resolve the dependency. Do dependencies of a Kotlin JS project have to be JS dependencies too?
I think I need my interface in a kotlin-common project, not JVM?
h

Hanno

07/03/2020, 4:51 AM
Yes, that's the answer
m

Matteo Mirk

07/03/2020, 8:27 AM
yes, that interface must be declared with the
expect
modifier and a platform-specific implementation with
actual
: https://kotlinlang.org/docs/reference/multiplatform.html#how-it-works
a

araqnid

07/03/2020, 9:00 AM
Or the interface can simply be defined in common, and the implementation defined in the platform subproject: you don’t need expect/actual for that
☝️ 1
View count: 1