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

    Alec Muffett

    12/02/2020, 10:06 AM
    Hi All! I am looking for some ideas and perspectives on deserialisation, delegation, and type-safety, please. For the sake of argument, I am using
    Protobuf
    and Square's
    Wire
    to serialise data, and to deserialise into Kotlin. Just like the example at https://github.com/square/wire#protocol-buffers I have a common
    Dinosaur
    message which has got a
    name
    string  The first and obvious change in the direction that I want to go, would be to replace the
    name
    with a protobuf
    enum
    so that I get
    Dinosaur.STEGOSAURUS
    (etc) as a nameEnum, which means that the code can find out the soft-type of the message; but that doesn't give me what I want. The second approach would be to use the protobuf
    oneof
    type - and it would essentially do exactly the same soft-type thing - I could use
    Dinosaur.STEGOSAURUS.foo.bar
    - but that still does not give me what I want. What I want is for the deserialisation process of a
    Dinosaur
    message to yield a
    Stegosaurus
    type; or a
    TRex
    or
    Apatosaurus
    type, or whatever, so that resulting code can guarantee having an
    Apatosaurus
    passed into it. I am presuming that some sort of
    DinosaurParser.peekType()
    and
    DinosaurParser.getApatosaurusOrThrow()
    will be needed, along with a type-enforcement
    is/as
    check. But that leaves me with the question of delegation so that I can access the other fields of the
    Dinosaur
    message, like height, weight, etc. • what's the best way for me to convert a "Dinosaur-message-with-TRex-soft-type" in the serialisation domain • into a kotlin-domain strongly-typed-instance-of-
    TRex
    that the compiler can check • but also inherit (delegate?) all the accessors and methods from the underlying
    Dinosaur
    message, into the
    TRex
    instance? It would be nice to do:
    class TRex(d: Dinosaur) : Dinosaur by d
    ...however the protobuf compilers are generating
    Dinosaur
    classes, not interfaces, so I don't think that option is open to me?
    • 1
    • 3
  • n

    Nick

    12/02/2020, 10:44 PM
    Our backend sends me ARGB values where the RGB is 0-255, but the alpha channel is 0-1. What’s the best way for me to scale the 0-1 to be the same as 0-255?
    n
    • 2
    • 2
  • n

    nkiesel

    12/02/2020, 11:00 PM
    I have the following code
    private const val TIME_OUT = 10000 // in milliseconds
            private val config = RequestConfig.custom()
                .setConnectTimeout(TIME_OUT)
                .setConnectionRequestTimeout(TIME_OUT)
                .setSocketTimeout(TIME_OUT)
                .build()
    I only need
    TIME_OUT
    for this initialization. How can I avoid having it hanging around? One idea I had was
    private val config = 10_000.let { timeOut ->
                RequestConfig.custom()
                    .setConnectTimeout(timeOut)
                    .setConnectionRequestTimeout(timeOut)
                    .setSocketTimeout(timeOut)
                    .build()
            }
    but that is not pretty either. Are there better ways?
    n
    c
    j
    • 4
    • 12
  • s

    sindrenm

    12/03/2020, 9:36 AM
    Does anyone have any idea why
    kotlinCompilerClasspath
    would downgrade my Kotlin version from 1.4.20 → 1.4.10, or could perhaps point me in the right direction on where to look? I see this when I run `./gradlew dependencies`:
    kotlinCompilerClasspath
    +--- org.jetbrains.kotlin:kotlin-compiler-embeddable:1.4.20 -> 1.4.10
    |    +--- org.jetbrains.kotlin:kotlin-stdlib:1.4.10
    |    |    +--- org.jetbrains.kotlin:kotlin-stdlib-common:1.4.10
    |    |    \--- org.jetbrains:annotations:13.0
    |    +--- org.jetbrains.kotlin:kotlin-script-runtime:1.4.10
    |    +--- org.jetbrains.kotlin:kotlin-reflect:1.4.10
    |    |    \--- org.jetbrains.kotlin:kotlin-stdlib:1.4.10 (*)
    |    +--- org.jetbrains.kotlin:kotlin-daemon-embeddable:1.4.10
    |    \--- org.jetbrains.intellij.deps:trove4j:1.0.20181211
    \--- org.jetbrains.kotlin:kotlin-compiler-embeddable:1.4.10 (*)
    There are no (direct) references to 1.4.10 in my dependency declarations, either. And that's the only place where I see the downgrade to 1.4.10. My Kotlin dependencies:
    object Kotlin {
        const val version = "1.4.20"
    
        const val gradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:$version"
        const val stdLib = "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$version"
    }
    k
    n
    • 3
    • 13
  • j

    Joao Birk

    12/03/2020, 3:01 PM
    Hi there, quick question about split method for String if I have val v = "" then I do v.split(".") I expect the method to return an empty List, but it actually returns a list with one element, and that element is my original string "" I can confirm that by looking at the code:
    private fun CharSequence.split(delimiter: String, ignoreCase: Boolean, limit: Int): List<String> {
        require(limit >= 0, { "Limit must be non-negative, but was $limit." })
    
        var currentOffset = 0
        var nextIndex = indexOf(delimiter, currentOffset, ignoreCase)
        if (nextIndex == -1 || limit == 1) {
            return listOf(this.toString())  -- HERE IT IS
        }
    Is this a behavior i should expect?
    v
    • 2
    • 8
  • s

    SanbosayDev

    12/03/2020, 3:30 PM
    Can someone help me with this please I keep getting failed to compiled values files every time I run the app. I have invalidated the cache and restarted the project but still getting the same error. I also added this dependency nothing worked implementation ‘androidx.core:core-ktx:1.3.2’
    v
    c
    • 3
    • 59
  • n

    Nir

    12/03/2020, 3:42 PM
    It seems kind of concerning that everything in the standard library that counts things, returns integers, accepts an index, etc, always seems to use
    Int
    . This seems like a pretty odd choice. Is there any way to instead have the standard library use a 64 bit integer?
    c
    e
    +3
    • 6
    • 113
  • p

    Patrik Åkerfeldt

    12/03/2020, 5:34 PM
    Suppose I have:
    annotation class MyAnnotation(val someValue: String, val optionalClass: KClass<*> = MyDefaultImplementation::class)
    
    interface MyInterface {
        fun doSomething(input: Any?): Any?
    }
    
    class MyDefaultImplementation: MyInterface {
        override fun doSomething(input: Any?): Any? = input.toString()
    }
    How can I set a bound on
    optionalClass
    to make sure only a class which implements
    MyInterface
    is provided?
    e
    • 2
    • 2
  • p

    Pratik Tandel

    12/03/2020, 10:56 PM
    how are enum classes implemented on the JVM? do they produce code that’s similar to a java
    enum
    ? asking because i’m trying to figure out how swagger annotations work and if i can rename them
    r
    z
    • 3
    • 8
  • k

    KV

    12/04/2020, 5:31 AM
    Hello people, I have a question about the hotifix versioning. Suppose I released the app with minor fix which is from 
    1.1.1
     to 
    1.1.2
      and in this version I stopped the rollout because we found out that there is some bugs. So I created the new branch 
    hotfix/1.1.2
     from the 
    release/1.1.2
     branch and merge the changes into 
    release/1.1.2
     branch. But now the question is 1. Is this correct to fix the issue on the 
    release/1.1.2
      branch? 2. What version we should use for the hotfix release? should we use 
    release/1.1.2
     or 
    release/1.1.3
     ? 3. Should we merge the 
    hotfix
     branch to 
    release/1.1.2
     branch or first do we need to create the new branch 
    release/1.1.3
     and merge hotfix changes into new branch?
    t
    v
    • 3
    • 3
  • p

    Paul Woitaschek

    12/04/2020, 7:24 AM
    The kotlin duration is killing me:
    (200.days + 5.nanoseconds - 200.days).toLongNanoseconds()
    This evaluates to
    4
    , not
    5
    .
    c
    e
    +4
    • 7
    • 69
  • m

    Mark

    12/04/2020, 7:35 AM
    When calling
    String.replace(String, String)
    for an unlikely replacement, does it ever makes sense to wrap in a
    CharSequence.contains(CharSequence)
    call, for efficiency?
    v
    • 2
    • 9
  • j

    Julius Marozas

    12/04/2020, 12:08 PM
    Hi, I am trying to understand why this 'when' expression is not exhaustive:
    sealed class Fruit {
        object Apple : Fruit()
        object Orange : Fruit()
    }
    
    fun <T : Fruit> eat(fruit: T): Unit =
        // 'when' expression must be exhaustive, add necessary 'else' branch
        when (fruit) {
            is Fruit.Apple -> {}
            is Fruit.Orange -> {}
        }
    This is just a contrived example, I know that I could simply inline 'T' with 'Fruit'. I am more interested to understand why Kotlin fails to see that the 'when' expression is exhaustive.
    v
    j
    t
    • 4
    • 11
  • g

    grahamborland

    12/04/2020, 2:16 PM
    Apparently it’s OK to pass null down a Flow, and Flow is intended to be compliant with the Reactive Streams spec. But the Reactive Streams spec disallows null, which is why RxJava 2 had that massive breaking change. I’m getting confused about something… why can a Flow handle null, but Rx2 can’t?
    z
    • 2
    • 3
  • f

    frogger

    12/04/2020, 2:20 PM
    is there a built-in method that lets me filter a
    Map<K,V?>
    to
    Map<K,V>
    ? I.e. filter all null values and cast the map?
    r
    v
    t
    • 4
    • 9
  • n

    Nir

    12/04/2020, 7:25 PM
    If we're writing some kind of not-completely-trivial transformation that can work on both sequences and iterables (as most can), it's pretty common to have to write the function twice. Is there a convention for which one should call which, in terms of the best performance? Or is there some preferred way to share code in a third function/object? Or should the code just be copy pasted? I guess usually the version that runs on iterable is the one that gets
    inline
    , so perhaps you'd want the sequence version to call the iterable version?
    t
    e
    • 3
    • 162
  • d

    Dieter Konrad

    12/04/2020, 7:37 PM
    That is not true: “It is not required to match directories and packages: source files can be placed arbitrarily in the file system.” — Language Guide https://kotlinlang.org/docs/reference/basic-syntax.html
    v
    t
    • 3
    • 10
  • d

    Dieter Konrad

    12/04/2020, 9:24 PM
    This is also wrong: “The return type is not specified, which means that the function returns nothing.” — Examples https://play.kotlinlang.org/byExample/01_introduction/01_Hello%20world cause it returns Unit — https://pl.kotl.in/-E3uqRzER
    n
    t
    a
    • 4
    • 10
  • u

    _shtomar

    12/04/2020, 10:37 PM
    i am not seeing KMM project template.
    c
    • 2
    • 1
  • b

    bjonnh

    12/05/2020, 7:03 PM
    Why is there no pow function for integers?
    a
    n
    d
    • 4
    • 23
  • l

    LastExceed

    12/06/2020, 2:09 PM
    I have a
    List<String>
    that i'd like to split into a
    List<List<String>>
    by indicating a delimiter
    String
    , similar to how i can split a
    String
    into a
    List<String>
    by indicating a delimiter
    Char
    using
    .split()
    . unfortunately lists dont have a
    .split()
    function, so what would be the best way to implement it ? looking for a functional approach if possible
    e
    e
    +3
    • 6
    • 23
  • j

    julian

    12/06/2020, 5:33 PM
    I have this -
    interface A {
        val na: Int
    }
    class B {
        val <T: A> T.nb: Int by lazy {
            <http://this.na|this.na> // !!! I want to reference T/A here, not B.
        }
    }
    I want to reference
    T : A
    but the compiler won't let me.
    this
    -s type is
    B
    . Is there another way?
    n
    a
    • 3
    • 5
  • e

    Ekaterina Volodko [JB]

    12/07/2020, 11:52 AM
    📢 Revamped :kotlin: Documentation – Give It a Try Hi all! We’re revamping our Kotlin documentation to bring you more helpful features and improve your user experience. To name just a few advantages, the new Kotlin documentation: • Is mobile friendly. • Has a completely new look and improved structure. • Provides easy navigation on each page. • Lets you share feedback on every page. • Lets you copy code with a single click. More features such as dark theme support are coming soon. Before going to production and deprecating the current version of the documentation, we want to ensure that we haven’t missed any critical issues. We’d be extremely grateful if you would look through the new revamped documentation and share your feedback with us. 👀 View new documentation When you view the Kotlin documentation you’ll still see it in the old format. To view the documentation in the new revamped format, click this link. This will add a cookie to your browser which will enable you to see the documentation in the new format. If you want to check anything in the old version of the documentation, open the usual link in another browser or use an incognito window in your current browser. 🗣️ Share your feedback 🤗 Your feedback is very important for us. You can: • Share feedback in the #docs-revamped channel. • Report an issue to our issue tracker. • Email us at doc-feedback@kotlinlang.org Try out the new documentation now!
    👍 3
    :blob-thinking-upside-down: 1
    :kotlin-intensifies: 27
    👏 28
    n
    i
    a
    • 4
    • 7
  • v

    Vivek Modi

    12/07/2020, 12:49 PM
    b
    e
    • 3
    • 3
  • n

    Nowak

    12/07/2020, 3:24 PM
    Does anyone know how to make something like this 🙂 ? I want to have type hints for reaction based on T class extended DomainEvent.
    val chainReactions: ChainReactions = mutableMapOf()
    typealias ChainReactions = MutableMap<DomainEvent, DomainEvent>
    ❓ 1
    r
    b
    • 3
    • 8
  • j

    Javier

    12/07/2020, 6:48 PM
    I am using
    Thread.currentThread()
    to obtain the line number, the problem is when I use a
    inline fun
    this number is not valid and I can’t see a pattern to fix it. Is there a workaround to this problem?
    • 1
    • 1
  • s

    StavFX

    12/07/2020, 7:07 PM
    I noticed that if I create a class whose primary constructor contains only parameters with default values - an empty constructor is available for Java code to call, without the use of
    @JvmOverloads
    e.g.
    class Foo(s: String? = null, i: Int = 3) // `new Foo();` from Java compiles
    However, that’s not the case when using a secondary constructor e.g.
    class Foo {
       constructor(s: String? = null, i: Int = 3) // `new Foo();` from Java does not compiles
    }
    Is this behavior documented somewhere? I couldn’t find anything..
    o
    v
    • 3
    • 8
  • p

    Philipp Mayer

    12/07/2020, 9:08 PM
    How could I design the following code in a more functional, immutable way? There's a single string where I want to throw multiple regexes on it. The size of the list of regex is flexible, so I can't operate over a set range. I'm actually refactoring some guys code and it grinds my gears that I cannot come up with a simpler solution for that:
    var label = when {
        ..someConditions.. -> "someString"
        else -> ""
    }
    
    regexes.forEach {
        label = label.replace(it.toRegex(), "").trim()
    }
    
    return label
    I should maybe just step away from it for some time.. 😄 any hint is appreciated, thanks!
    e
    n
    +2
    • 5
    • 16
  • s

    Simon Lin

    12/08/2020, 2:07 AM
    Hi everyone, I would like to know where the kotlin project people usually to save? For example, the android project usually saved in
    ~/AndroidStudioProjects/
    . How about non-android project?
    a
    m
    +5
    • 8
    • 11
  • b

    Brian Dilley

    12/08/2020, 4:28 AM
    If my Kotlin library depends on JVM classes - is it best to just distribute it as a java library rather than a kotlin library?
    r
    • 2
    • 7
Powered by Linen
Title
b

Brian Dilley

12/08/2020, 4:28 AM
If my Kotlin library depends on JVM classes - is it best to just distribute it as a java library rather than a kotlin library?
r

Rob Elliot

12/08/2020, 7:23 AM
What’s the difference?
b

Brian Dilley

12/08/2020, 8:45 AM
Well, if my library was pure Kotlin and could be used by KotlinNative, or KotlinJS, etc. then i’d probably want it to be distributed differently.
but then again I guess that’s just a question of packaging anyway. But If i recall correctly with the latest version of kotlin there’s a way to distribute an all-kotlin library that isn’t quite JS, JVM, etc.
it’s in the IR format or something
r

Rob Elliot

12/08/2020, 9:00 AM
I’d be surprised if you were intended to distribute the IR… wouldn’t it then require a runtime interpreter for each target, which would be pretty expensive I’d have thought? My uneducated assumption was that the IR was a compilation half way house to a common format that was then easy to compile into the target formats, allowing code sharing and efficiency gains when compiling for multiple targets, but that we would still distribute libraries in the different target formats. But I confess to that being pure assumption.
b

Brian Dilley

12/08/2020, 9:04 AM
https://kotlinlang.org/docs/reference/mpp-intro.html
but I think it just builds libraries for every supported platform
View count: 4