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

    ShootingStar

    12/17/2019, 1:05 PM
    What is the meaning in this context?
    m
    i
    +2
    • 5
    • 5
  • s

    steenooo

    12/17/2019, 3:48 PM
    It is possible to have Java and Kotlin in the same package right?
    :yes: 3
    h
    m
    • 3
    • 11
  • s

    Sylvain Patenaude

    12/17/2019, 8:21 PM
    Is there by any chance an equivalent in Kotlin of .NET
    Enumerable.Select
    to convert from enumeration<type1> to enumeration<type2>? Thanks!
    b
    • 2
    • 7
  • w

    Willy Njundong

    12/17/2019, 9:11 PM
    how do i create data objects in kotlin similarly to what i could do with javascript:
    const myObject = {
      someKey: someValue,
      someOtherKey: [{foo: "bar"}, {bar: "foo"}]
    }
    c
    m
    • 3
    • 2
  • j

    jameswald

    12/18/2019, 3:28 AM
    is there any way to mark the class generated by
    @file:JvmName("...")
    as
    @Deprecated
    ?
    s
    t
    • 3
    • 7
  • n

    New111

    12/18/2019, 8:53 AM
    Hi all, I have the following code:
    ProcessBuilder("/bin/sh", "-c",
          "java -jar $jarName -f $configName ${args.joinToString(" ")} &")
          .start()
    how can I redirect stdout of the child to stdout of the parent process (so I could see all the messages together) ? The following code using
    inheritIO
    doesn't work either:
    ProcessBuilder("/bin/sh", "-c",
            "java -jar $jarName -f $configName ${args.joinToString(" ")} &")
            .inheritIO()
            .start()
    Any clue where the problem is ? Is it somehow related to the fact that the child process writes to log file ?
    s
    a
    • 3
    • 17
  • b

    Bruno_

    12/18/2019, 11:03 AM
    but when I do Foo..Foo its a type of ClosedRange<Foo> insead of FooRange that I've implemented
    d
    • 2
    • 8
  • w

    Wesley Acheson

    12/18/2019, 12:23 PM
    whats the best way to convert from a list of objects (think database results) to a nested object set. For instance a JDBC results set that used
    GROUP BY day, status
    which would give me a list with the same day more than once and the same status more than once which returned a list of
    data class DayStatusCount(val day:LocalDate, val status:Status, val count:Long)
    If I wanted to convert to a
    Map<LocalDate, Map<Status, Long>>
    or anythings similar to that. I've been creating mutable maps.
    val rawData: MutableMap<LocalDate, Map<Status, Long> = HashMap()
            data.forEach {
                rawData
                        .getOrPut(it.day) { HashMap() }
                        .getOrPut(it.status) { HashMap() }
    // More as per step
            }
    Sorry thats not the real code. but anyway convert from a list with duplicates to nested sets.
    u
    r
    • 3
    • 17
  • j

    Joan Colmenero

    12/18/2019, 12:50 PM
    How can I sort by a method that returns Boolean in Kotlin? I was using
    Comparator
    which returns an
    Int
    but now I need more complex stuff, so I have a method that returns
    True
    or
    False
    depending of a check, is there any way I'd use this method to sort it? Is getting
    Foo1
    Foo2
    as a parameter and then do the comparation.
    d
    • 2
    • 46
  • s

    Slackbot

    12/18/2019, 2:22 PM
    This message was deleted.
    r
    w
    • 3
    • 5
  • l

    Lauritz Hilsøe

    12/18/2019, 2:46 PM
    We have an API endpoint that receives XML data from a 3rd party provider. The data itself is basically a list of elements, where each can be one of many different polymorphic types. They all share some attributes (say they all have a created_at="") and then some specific per element. Looked into using Jackson but it all seem very cumbersome, whats' the easiest way to parse this XML? An example could be
    <?xml version="1.0" encoding="UTF-8">
    <provider version="1.0">
      <update id="12313">
        <event name="hello" created_at="2019-12-14" />
        <event name="world" created_at="2019-12-16" />
        <country where="us" created_at="2019-15-16" />
      </update>
    </provider>
    Basically want to end up with a class containing
    ProviderUpdate(id: String, updates: List<Update>)
    where
    Update
    is either an interface, class, sealed class or something, that can either be
    Event
    or
    Country
    or etc
    w
    m
    • 3
    • 3
  • s

    Sylvain Patenaude

    12/18/2019, 4:19 PM
    How do you deal with "flag" enums in Kotlin? Let's say I have flags 1,2,4,8 in my enum and from parsing some data, I obtain 5 (1 and 4 combined). How do I convert that 5 back into some enum value? In .NET, you have these "flag" enums and they are quite useful.
    t
    a
    m
    • 4
    • 8
  • s

    sandjelkovic

    12/18/2019, 6:04 PM
    Why is
    lateinit var
    not allowed for inline classes that wrap types that otherwise can be
    lateinit
    -ed? For example:
    inline class Id(val value: String)
    can’t be used as
    private lateinit var id: Id
    and is there a workaround that is not a nullable field or a data class?
    s
    • 2
    • 4
  • e

    elect

    12/18/2019, 7:54 PM
    if I have the following:
    inline fun defaultCheck(result: VkResult) = result.check()
    
    fun bar(check: (VkResult) -> Unit = ::defaultCheck) {
       check(..)
    }
    would there be any allocation regarding passing the lambda to
    bar
    ?
    d
    • 2
    • 3
  • d

    Dariusz Kuc

    12/18/2019, 8:56 PM
    hello! by any chance anyone knows what might be causing the difference in the behavior of reading binary content from file?
    javaClass.classLoader.getResource("myFile").readBytes()  // 198
    File("myFile").inputStream().readBytes() // 184
    If I'm reading input stream from a resource (which I have to in deployed app) I get some extra bytes that I do not get if I read the file directly. Any ideas?
    • 1
    • 1
  • j

    Joffrey

    12/19/2019, 10:24 AM
    Hi guys, the stdlib
    fun List<Pair<K,V>>.toMap()
    drops duplicate entries without providing a way to merge them. Is there a stdlib function that can do this? I often need this when dealing with maps containing quantities. I implement it this way:
    fun <K, V> List<Pair<K, V>>.toMap(combine: (V, V) -> V?): Map<K, V> {
        val result = mutableMapOf<K, V>()
        for ((k, v) in this) {
            result.merge(k, v, combine)
        }
        return result
    }
    Another one I'm missing is merging 2 maps provided a function to recombine the values of keys that are present in both maps.
    m
    m
    • 3
    • 16
  • r

    Ray Eldath

    12/19/2019, 11:58 AM
    hi everyone. I want to know why there isn't something like
    lateinit val
    which is immutable after the initialization...? in my practice actually my
    lateinit
    is always for this immutable occasion... A friend of mine said that in the early version of Kotlin there is something like that, but then it's withdrawn. BTW, in KotlinConf 2018 Closing Panel many a speaker regarded
    lateinit
    as their most annoying Kotlin feature, and seems lots of audience agreed the opinion. I am wondering if this is because of the problem mentioned above...
    c
    • 2
    • 1
  • a

    Anders Mikkelsen

    12/19/2019, 12:09 PM
    Probably only incidental, if lateinit did not exist, the culprit would be var some: Something?. If you need a deferred val, use by lazy {}. Problem is often with injection i guess. Which is where the antagonizing of lateinit comes from i believe.
    m
    r
    • 3
    • 9
  • a

    andyg

    12/19/2019, 12:11 PM
    Hi, getting back into Kotlin (on the server) after being away for a while. Searching for idiomatic Kotlin examples of a basic CRUD class, without Hibernate or other ORM. Is it possible for the class to have its own .save() and .get() methods, and also to have immutable (val) internal data? (i.e. want to avoid the
    var id:Int = 0
    boilerplate, because once established, all values should be immutable, and no instance should ever have id = 0) Thanks 🙂
    m
    • 2
    • 6
  • j

    jeggy

    12/19/2019, 2:34 PM
    Is it possible to do a negative infix operator? I currently have this operator:
    infix operator fun contains(option: Option): Boolean
    I would like to be able to write both cases
    if (data contains MyOption)
    and
    if (data !contains MyOption)
    g
    s
    • 3
    • 14
  • a

    Andreas Unterweger

    12/19/2019, 3:27 PM
    hello, a question related to SAM functional interfaces
    interface RequestAuth {
        fun header(): Pair<String, String>
    }
    val instance = object : RequestAuth {
                    override fun header(): Pair<String, String> = "name" to "value"
                }
    cant this be done more more concisely? sth like
    val instance = object : RequestAuth { "name" to "value" }
    d
    m
    • 3
    • 4
  • j

    jmfayard

    12/19/2019, 3:49 PM
    I want to write fast Kotlin code on on website that provides algorithm challenges with large amount of data that's something new to me any tips?
    a
    • 2
    • 2
  • s

    Slackbot

    12/19/2019, 4:52 PM
    This message was deleted.
    l
    • 2
    • 2
  • j

    John

    12/19/2019, 5:58 PM
    How would you have a data class inheriting a sealed class and its variables without having to pass them, something like
    sealed class Source(
        @Json(name = "value")
        val value: String,
        @Json(name = "value2")
        val value2: Boolean
    ) {
        object Source1: Source
        object Source2: Source
    }
    m
    s
    • 3
    • 11
  • j

    Jannis

    12/19/2019, 6:19 PM
    Hi, is this behaviour a known bug? Or is this supposed to happen?
    generateSequence(0) { it + 1 }.take(100000).fold(emptySequence<Int>()) { acc, v ->
            acc + v
          }.first() => stackoverflows
    Also this works fine:
    generateSequence(0) { it + 1 }.take(100000).fold(emptySequence<Int>()) { acc, v ->
            sequenceOf(v) + acc
          }.first() => works fine
    👍🏼 1
    k
    • 2
    • 32
  • w

    Will Nixon

    12/19/2019, 9:18 PM
    Hi all, coming from Swift development, I’m able to store some user defaults / persist some small items using something called CoreData (for those who’ve not heard of it). What would the equivalent be for Kotlin/Android development to persist some user data?
    r
    k
    +3
    • 6
    • 16
  • k

    kpgalligan

    12/19/2019, 9:25 PM
    Is general a good place to ask about best channel for a topic that isn’t super obvious? Looking for low hanging fruit with psi https://www.jetbrains.org/intellij/sdk/docs/basics/architectural_overview/psi_elements.html. For detekt/lint stuff but also maybe intellij plugins?
    p
    r
    • 3
    • 3
  • j

    Jérôme Gully

    12/20/2019, 4:08 PM
    Hi, someone have used kotlinx.cli ? I try to add it as dependeny but I never can use it in my code. https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-cli/0.2.0-dev-7
    repositories {
        mavenCentral()
        maven { url = uri("<https://dl.bintray.com/kotlin/kotlin-dev>") }
    }
    
    dependencies {
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
        implementation "org.jetbrains.kotlinx:kotlinx-cli:0.2.0-dev-7"
    }
    
    fun main(args: Array<String>) {
        val parser = ArgParser() // ArgParser not found
    }
    • 1
    • 2
  • s

    Sylvain Patenaude

    12/20/2019, 9:15 PM
    Is it possible to have something like/similar to this in Kotlin? object O { fun <T> f1(param: T) { f2(param) } private fun f2(i: Int) {...} private fun f2(f: Float) {...} } O.f1(123) O.f1(123.45f)
    s
    d
    +3
    • 6
    • 51
  • o

    Ofir Bar

    12/21/2019, 1:31 PM
    hello my friends 🤩 😛 A question please- I have a ClickableSpan() object that I am passing to a method I made named “setLinksWithinText”. ClickableSpan() has an abstract method “onClick”. I want to pass only the onClick implementation and not the entire ClickableSpan() object to the method i made. This is because ClickableSpan() also have a method updateDrawState and I want to set the updateDrawState in my setLinksWithinText method. This is how I instantiate the ClickableSpan() now:
    val customClickSpan = object : ClickableSpan() {
        override fun onClick(widget: View) {
            Toast.makeText(widget.context, "Click worked!", Toast.LENGTH_SHORT).show()
        }
    
        override fun updateDrawState(ds: TextPaint) {
            super.updateDrawState(ds)
            ds.color = Color.RED
            ds.isUnderlineText = true
        }
    }
    And then I pass it to my method:
    fun setLinksWithinText(stringResource : CharSequence, clickListener : ClickableSpan) : SpannableString {
        val stringResourceSpanned = stringResource as SpannedString
        val annotations = stringResourceSpanned.getSpans(0, stringResourceSpanned.length, android.text.Annotation::class.java)
        val spannableString = SpannableString(stringResourceSpanned)
    
    
        for (annotation in annotations) {
            // look for the span with the key "font"
            if (annotation.key == "text_type") {
                val textType = annotation.value
    
                if (textType == "link") {
                    spannableString.setSpan(
                        clickListener,
                        stringResourceSpanned.getSpanStart(annotation),
                        stringResourceSpanned.getSpanEnd(annotation),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                }
            }
        }
    
        return spannableString
    }
    s
    • 2
    • 1
Powered by Linen
Title
o

Ofir Bar

12/21/2019, 1:31 PM
hello my friends 🤩 😛 A question please- I have a ClickableSpan() object that I am passing to a method I made named “setLinksWithinText”. ClickableSpan() has an abstract method “onClick”. I want to pass only the onClick implementation and not the entire ClickableSpan() object to the method i made. This is because ClickableSpan() also have a method updateDrawState and I want to set the updateDrawState in my setLinksWithinText method. This is how I instantiate the ClickableSpan() now:
val customClickSpan = object : ClickableSpan() {
    override fun onClick(widget: View) {
        Toast.makeText(widget.context, "Click worked!", Toast.LENGTH_SHORT).show()
    }

    override fun updateDrawState(ds: TextPaint) {
        super.updateDrawState(ds)
        ds.color = Color.RED
        ds.isUnderlineText = true
    }
}
And then I pass it to my method:
fun setLinksWithinText(stringResource : CharSequence, clickListener : ClickableSpan) : SpannableString {
    val stringResourceSpanned = stringResource as SpannedString
    val annotations = stringResourceSpanned.getSpans(0, stringResourceSpanned.length, android.text.Annotation::class.java)
    val spannableString = SpannableString(stringResourceSpanned)


    for (annotation in annotations) {
        // look for the span with the key "font"
        if (annotation.key == "text_type") {
            val textType = annotation.value

            if (textType == "link") {
                spannableString.setSpan(
                    clickListener,
                    stringResourceSpanned.getSpanStart(annotation),
                    stringResourceSpanned.getSpanEnd(annotation),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
    }

    return spannableString
}
s

Siyamed

12/21/2019, 1:50 PM
Afaik, dont set the same object to different parts of the spannable. Create a new clickable span. For click delegation, create a wrapper and call onclick from your own wrapper which also extends clickable span.
View count: 9