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

    alllex

    12/16/2020, 3:34 PM
    Can anyone explain why this snippet compiles (and executes) without errors? (
    get
    operator in kotlin is strictly typed)
    fun main() {
        val intList: List<Int> = listOf(1, 2)
        val stringMap: Map<String, String> = mapOf("abc" to "xyz")
        val x = intList.associateWith { map[it] } // should be an error, because key is String, and not Int
        println(x)
    }
    Kotlin: 1.4.21
    i
    • 2
    • 3
  • r

    Rob Elliot

    12/16/2020, 4:00 PM
    Is it possible to use
    kotlinc
    programatically? I’d like to compile a kotlin class from a kotlin source file in a JVM app at runtime.
    m
    v
    • 3
    • 6
  • r

    Rob Elliot

    12/16/2020, 4:05 PM
    Second question - I’d like to enforce, at compile time, that some compiled code does no I/O. Obviously I can control what dependencies are available to it, but is there a relatively easy way to (comprehensively!) exclude all Java & Kotlin stdlib classes that do I/O, directly or transitively, from compilation? I suspect no, but I do feel that being able to enforce at compile time a strong separation of concerns between code that does and does not do I/O would be useful.
    m
    y
    • 3
    • 15
  • e

    Edoardo Luppi

    12/16/2020, 6:53 PM
    When developing for JVM, I can run my code from the
    main
    function. When on multiplatform, is there a way to do the same thing for JS?
    m
    • 2
    • 1
  • g

    Grant Park

    12/16/2020, 10:14 PM
    I’ve heard a rumor that the
    when
    statement can evaluate its cases in constant time, because the compiler will change the switch structure to a map. Does anyone know if this is true?
    m
    n
    +2
    • 5
    • 68
  • r

    rocketraman

    12/17/2020, 1:03 AM
    Has anyone thought about contributing a Kotlin pattern for git's function detection in diffs? https://github.com/git/git/blob/master/userdiff.c
    👍 1
    n
    • 2
    • 4
  • z

    zain

    12/17/2020, 4:34 AM
    How do you upsert a list of objects in Java or in Kotlin. What is the best practice or the best chain for something like upserting a setting. Scenario one match-id can have many settings and that can change.
    data class Setting(val typeId: Int, val type: String, val isSubscribed: Boolean, val matchId: Int)
    
        val settings = mutableListOf(Setting(1, "Goal Notification", true, matchId = 123), Setting(2, "Half Time Notification", true, matchId = 567))
    
        //upsert?/
        val newSettings = settings.add(Setting(1, "Goal Notification", false, matchId = 123))
    
        val latestSettings = settings.filter { setting -> setting.typeId == 1 }.map {
            // add or update over here
        }
    o
    • 2
    • 2
  • z

    zokipirlo

    12/17/2020, 8:21 AM
    Hi! I have one question regarding lazy variables. Is something like that possible?
    val myNotRequiredStuff : SomeClass by lazy { SomeClass(...) }
    ...
    fun onDestroy() {
        myNotRequiredStuff.useIfCreated {
            myNotRequiredStuff.destroy()
        }
    }
    o
    j
    m
    • 4
    • 8
  • b

    Benjamin Vallet

    12/17/2020, 9:11 AM
    I am passing a pickle object from a python software through a TCP socket and receiving it in my kotlin application. Does anyone know how I could unpickle it to retrieve my data ?
    r
    a
    • 3
    • 9
  • i

    ikej

    12/17/2020, 9:45 AM
    After upgrading the IDE plugin to 1.4.21, the plugin now throws Gradle-related exceptions all the time and there is no code completion in .gradle-kts files anymore. After downgrading to 1.4.10 it works again. I cannot find a 1.4.20 release for 2020.3. Does anybody know a page where you can see all releases?
    k
    a
    m
    • 4
    • 16
  • p

    Peter Ertl

    12/17/2020, 1:58 PM
    is it possible to declare a generic type that is kotlinx-serializable? something like. <T : “i am serializable”>
    🇳🇴 2
    r
    m
    • 3
    • 5
  • p

    Peter Ertl

    12/17/2020, 3:03 PM
    how can I use kotlin-reflect to get all subclasses of an abstract base class? the base class is NOT sealed
    m
    t
    • 3
    • 34
  • c

    CLOVIS

    12/17/2020, 4:04 PM
    I have :
    interface A<T>
    I want to write a function that takes an
    A
    and a value of the same type. Intuitively, this would look like:
    fun <T> foo(a: A<T>, v: T)
    The problem is that if I call it this way:
    val a: A<String> = ...
    val v: Int = ...
    foo(a, v)
    It calls
    foo<Any>(a, v)
    , but I want it to call
    foo<String>(a, v)
    (and fail, because `v`'s type doesn't match what was expected by
    a
    ). This function is fairly simple, so solutions using
    reified
    or other
    inline
    mechanism are not a problem, but I don't see how to do it.
    a
    • 2
    • 1
  • l

    Lauren Yew

    12/17/2020, 4:10 PM
    Hi all, I want to define a kotlin function as a parameter for a class and I want that kotlin function to be able to have 0 or more arguments. Is there a way to do that? Ex:
    class Builder (
    private val function: (suspend () -> String) //Don't want to force Builder to have to provide a no argument function
    )
    Context: I used to be able to do this in RxJava with a Single. Moving to Coroutines / Flow.
    v
    y
    • 3
    • 15
  • u

    user

    12/17/2020, 4:33 PM
    Lets-Plot, in Kotlin You can understand a lot about data from metrics, checks, and basic statistics. However, as humans, we grasp trends and patterns way quicker when we see them with our own eyes. If there was ever a moment you wished you could easily and quickly visualize your data, and you were not sure how to do […]
    b
    n
    +2
    • 4
    • 5
  • j

    Joost Klitsie

    12/17/2020, 5:09 PM
    What is the current opinion on error/exception throwing in Kotlin? For me I try to avoid it as best as I can because there are no checked exceptions and therefore no IDE or compile time safety whatsoever. I wrap any source of exception (like a library call that might throw an error) into a Result object to avoid having unexpected errors thrown in my face. This is especially interesting for libraries. How do I know that a certain call might throw an error? It is therefore curious to me why there is so much support for catching errors, while it is impossible to know which piece of code might actually throw an error, without prior knowledge of the code itself. For example, Flows support error catching, but there is no way to know which operation might throw an error. So what is the "best" option? Should I wrap any error in a result object directly from the source (by wrapping library calls in try/catch)? Or should I throw unchecked errors and hope for the best that someone/some code down the line will catch them? Is there any pattern in this that is advised?
    j
    n
    +2
    • 5
    • 95
  • j

    James Ward

    12/17/2020, 6:45 PM
    Contentious question... What should I be using for testing & why?
    r
    r
    +2
    • 5
    • 5
  • n

    Nir

    12/17/2020, 10:33 PM
    I dont' actually think it's any code of mine in particular... the compiler is just producing a java.io.EOFException no matter what no
    • 1
    • 1
  • c

    Colton Idle

    12/18/2020, 12:37 AM
    Every time I build I get a bunch of these types of warnings:
    Parameter 'w' is never used, could be renamed to _
    Is there a way to auto fix all of these kotlin warnings? I know in android-lint you can select a group of issues and hit the fix button all in one shot.
    r
    a
    • 3
    • 5
  • s

    Slackbot

    12/18/2020, 7:57 AM
    This message was deleted.
    g
    j
    d
    • 4
    • 7
  • k

    KamilH

    12/18/2020, 9:58 AM
    I have a two ranges that represents a timeline of some media (whole media is 0..30000, but I have a ranges like 0..15000 and 15001..30000). I also have a list of ranges how long user listened to some part of the media. Is there any function in stdlib that lets me easily calculate how long user spent in which range? Media ranges (0..30_000): 0..15_000 and 15_001..30_000 Listened ranges: (0..10_000), (5_000..15_000), (20_000..25_000) Result would be: For (0..15_000) range = 20_000 For (15_001..30_000) range = 5_000
    • 1
    • 1
  • t

    tpgillam

    12/18/2020, 1:48 PM
    Hello - I am upgrading a project from Kotlin 1.3.72 to 1.4.21. As part of this, I had some code of the form
    val x = foo() ?: return moo
    , where
    foo(): T?
    is a method returning a nullable generic
    T?
    . Now previously,
    x
    was of type
    T
    , however now the IDE is telling me that it is of type
    T!!
    . I can seemingly force it to be of type
    T
    , however can somebody explain what is going on here? I also can't find the relevant part of documentation that explains what
    !!
    means when postfixing a (possibly only generic?) type. Thanks!
    m
    • 2
    • 20
  • a

    Animesh Sahu

    12/18/2020, 3:43 PM
    Is there a concise way to check the next statement, sort of:
    return when {
        cond1 -> try { something() } catch (e: Exception) { TODO() /* Goto cond2 */ }
        cond2 -> TODO()
        else -> throw RuntimeException("Whatever reason")
    }
    m
    e
    r
    • 4
    • 6
  • j

    janvladimirmostert

    12/18/2020, 4:44 PM
    What is a nice Kotlin way of copying data from a ByteArrayOutputStream in chunks to an OutputStream? the non-chunked way seems to be
    outputStream.use { out -> baos.writeTo(out) }
    d
    • 2
    • 7
  • n

    Nir

    12/18/2020, 7:30 PM
    also I realize it can probably be done via reflection, but want to avoid that
    n
    • 2
    • 5
  • a

    asad.awadia

    12/19/2020, 4:10 AM
    Is it possible to get something like
    code .
    In shell which opens VSCode in the current directory but for intellij? Like
    intellij .
    That launches intellij for the current dir - create or open if not exists the project
    a
    c
    +2
    • 5
    • 14
  • c

    christophsturm

    12/19/2020, 3:44 PM
    is there a collection method that returns all elements of a list before the last time a predicate is true? something like
    [1,2,3,4,5,4,6].takeUntilLast { it == 4}
    results in
    [1,2,3,4,5,4]
    r
    • 2
    • 3
  • n

    Nir

    12/19/2020, 5:05 PM
    What's the nicest + efficient way to do a map of some collections into sets, and flatten into a union of those sets? Right now I'm thinking:
    val finalSet = whateverlist.fold(mutableSetOf()) { acc, element ->
        val individualSet = someCode(element)
        acc.apply { addAll(individualSet) }
    }
    I'd expect this to be a little faster than some of the other approaches (e.g. reduce with regular Set and
    union
    )
    r
    • 2
    • 6
  • l

    Lulu

    12/19/2020, 6:50 PM
    I'm making a library that can make use of annotations, where it should get user-defined functions and classes annotated. I know how to define annotations and their target, but I'm lost when it comes to processing them. There seems to be kapt, Dagger and some others, but which one should I be using?
    n
    • 2
    • 6
  • n

    Nikky

    12/21/2020, 11:14 AM
    is there a compiler plugin in kotlin that can warn or error when passing a lambda to a `Any`/`Object` ? seems to hoppen now and then and always takes some time to figure out that someone used the wrong overload or maybe a plugin for IDEA and AS ?
    g
    l
    • 3
    • 4
Powered by Linen
Title
n

Nikky

12/21/2020, 11:14 AM
is there a compiler plugin in kotlin that can warn or error when passing a lambda to a `Any`/`Object` ? seems to hoppen now and then and always takes some time to figure out that someone used the wrong overload or maybe a plugin for IDEA and AS ?
g

gildor

12/21/2020, 1:29 PM
Passing lambda to Any?
🤷‍♂️ 1
l

LeoColman

12/21/2020, 4:25 PM
I think they meant like
foo( { x -> x + 1 } )

fun foo(any: Any) {}
It doesn't look like you want to call foo with a function, or else you'd written it as a high-level function
n

Nikky

12/21/2020, 9:25 PM
and there is a few java apis that have
Object...
as last arguments
View count: 3