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

    Phani Mahesh

    10/02/2020, 2:34 PM
    very very dumb question. I have a
    csvReader.open(file) { ... }
    function from a library. The problem is the lambda is not suspend-aware. Is there any way to call a suspend fn in the lambda there other than calling runBlocking? FWIW, this is all inside a suspending function, so I do not want to do
    runBlocking
    inside a
    suspend
    function. It just feels so wrong.
    n
    a
    • 3
    • 5
  • l

    LeoColman

    10/02/2020, 5:08 PM
    I'm trying to use Jacoco, but it detects a lot of classes that shouldn't have coverage, such as Kotlin synthetic classes
    s
    h
    • 3
    • 2
  • b

    bbaldino

    10/02/2020, 8:53 PM
    Is there a way to add a "scoped" extension to class A inside of class B, outside of class B? For example, I tried this but it complains:
    class Foo {
       fun String.someStringExtension() { ... }
    }
    
    fun Foo.String.someOtherStringExtension() { ... }
    a
    u
    • 3
    • 3
  • j

    Joel

    10/02/2020, 8:57 PM
    @bbaldino I looked this up one time and pretty certain this feature is still in proposal phase. I agree that it would be incredibly useful. I can't find a reference at the moment, but Kotlin language proposals are found here .
    b
    n
    n
    • 4
    • 49
  • a

    Animesh Sahu

    10/03/2020, 3:39 PM
    Can we have some sort of bounded (must-be-same) star projections?
    fun <T : SomeClass<*>> SomeOtherClass<*>.function() {...}
    Such that we can guarantee the two star-projections must be equal? I know we can introduce another generic, but that'll lead to redefine that explicitly twice like 
    function<T<E>, E>
     when calling the function. So is there any way we can omit that extra generic and use some implicit kind of thing?
    t
    • 2
    • 1
  • c

    CLOVIS

    10/04/2020, 2:10 PM
    Is the
    x
    is
    kotlinx
    for ‘extensions' (like in
    javax
    ) or for ‘experimental'?
    b
    • 2
    • 2
  • a

    addamsson

    10/04/2020, 2:49 PM
    Hi there! I've seen that with 1.4 SAM intefaces are now converted properly between Kotlin and Java. This is great, but there is a problem, however: I still can't define functions that return void. For example if I have a signature like this:
    fun someFun(fn: (SomeClass) -> Unit)
    I have to explicitly return
    Unit.INSTANCE
    from Java code. Is there a way to fix this (besides writing a helper function)
    🇳🇴 2
    b
    e
    • 3
    • 3
  • u

    Uzi Landsmann

    10/04/2020, 7:22 PM
    Looking at the experimental
    Duration
    implementation in
    kotlin.time
    I can see the extension methods from
    Int
    and
    Long
    to
    Duration
    . However I’d like to use the Java function:
    public static Duration ofSeconds(long seconds, long nanoAdjustment)
    …which I can’t see an implementation for. Any thoughts on how to achieve the same in kotlin?
    j
    • 2
    • 2
  • a

    Andrea Giuliano

    10/05/2020, 7:55 AM
    Hi folks! Is there a best alternative in Kotlin than using java nio Bytebuffer?
    val bos = ByteArrayOutputStream()
    DataOutputStream(bos).use {
       it.writeInt(mydata)
    }
    ByteBuffer.wrap(bos.toByteArray())
    I was googling around but haven’t found anything really.
    v
    z
    • 3
    • 3
  • z

    zeugederunity

    10/05/2020, 8:46 AM
    Hello everyone, does anyone know, why the first four functions return false?
    fun main() {
        fun main() {
        val arr1 = Array(0) { "" }::class
        val arr2 = arrayOf("")::class
        val arr3 = Array::class
    
        println(arr1 == Array::class)               //false
        println(arr1.isSubclassOf(Array::class))    //false
        println(arr2 == Array::class)               //false
        println(arr2.isSubclassOf(Array::class))    //false
        println(arr3 == Array::class)               //true
        println(arr3.isSubclassOf(Array::class))    //true
    }
    I think thats a bug.
    s
    • 2
    • 9
  • x

    Xitij

    10/05/2020, 8:49 AM
    suspend fun jobLifecycle () = coroutineScope {
       val job =  launch{
           println("Working....")
           delay(2000L)
           println("Done !")
        }
    
        delay(1000L)
        job.cancel() 
        // delay(1L) i have to do it to print correct value of job.isCompleted below
       
        println("isCompleted: ${job.isCompleted}") // it is printing "false" but if i delay for some time after cancelling the job it prints  "true".
       
    }
    is it my computer or it really takes some time to move job from cancelling to cancelled state where isCompleted becomes true after cancellation of job or is there something im missing out pls review..
    z
    • 2
    • 1
  • t

    Tobias G. Waaler

    10/05/2020, 10:30 AM
    Hi all, I have a java class with a method I want to override in my kotlin code. The method returns java.lang.Object, meaning it can possibly be null, and I would like to return null from my kotlin implementation. The problem is that I am not allowed to specify the return type of my method as
    Any?
    when the method I'm overloading has return type
    Object
    🤔
    d
    r
    • 3
    • 16
  • p

    Philipp Mayer

    10/05/2020, 11:49 AM
    Hey everyone! Today I finally started using sealed classes, which is great. But I came to a point where I'm not sure how to handle it in the correct way:
    .map { (payment, requestModel) -> steps.performRequest(payment, requestModel) 
    .filter { (_, result) -> result is ApiResult.Success }
    .map { (payment, result) -> steps.update(payment, result) }
    After performing the request, I want to filter out all results which were not of Type
    ApiResult.Success
    Unfortunately the compiler does not allow this, since
    update()
    is expecting
    ApiResult.Success
    . What did I miss there? My only solution right now is to set the
    result
    Parameter to ApiResult and add a
    require()
    block in my update function, but I'm not really happy with that.
    g
    v
    +2
    • 5
    • 20
  • v

    Vampire

    10/05/2020, 4:28 PM
    My brain is fried, I don't understand this, anyone a quick helping hand?
    Unnecessary safe call on a non-null receiver of type Int?
    Why is
    Int?
    non-null? Why is it wrong to use
    ?.
    on it?
    n
    j
    • 3
    • 15
  • u

    user

    10/05/2020, 5:43 PM
    Kotlin Public Roadmap Through Spring 2021 Today, we’re excited to announce the public roadmap for Kotlin. This document describes the biggest projects our team is working on right now. It has a 6-month time frame and will be updated every 3 months. Each item on the roadmap represents a project with a linked YouTrack ticket. If you have a question about […]
    👏 6
    ❤️ 9
    👍 2
    m
    • 1
    • 1
  • s

    Subhi Pandey

    10/05/2020, 6:10 PM
    hi i have a question deos kotlin have sound null safety?
    z
    d
    • 3
    • 2
  • m

    mike.holler

    10/05/2020, 8:03 PM
    👋 Hi there! I've been a Kotlin fan way back since M11 or so and am now starting to play with multi-platform. We've got some functions we'd like to share between JS and JVM runtimes, but we already have a JS-based application that we don't want to re-write in Kotlin quite yet. I've done the tutorial here [1], which is fantastic, but I'm not sure how I can use NPM to install it directly and call into the Kotlin library from my JavaScript project. Can anyone offer any pointers? I've maven-published the library, but I see no mention of NPM or how to use a kotlin library with NPM in this tutorial. [1]: https://kotlinlang.org/docs/tutorials/mpp/multiplatform-library.html
    b
    • 2
    • 5
  • s

    snowe

    10/05/2020, 11:09 PM
    having trouble converting a small bit of java to kotlin.
    for (Map<String, String> serviceOutputs; (serviceOutputs = resultReader.read(header)) != null; ) {
        try {
            final double elapsed = Double.parseDouble(serviceOutputs.get("__elapsed"));
    gets converted to
    var serviceOutputs: Map<String, String>
    while (resultReader.read(*header).also { serviceOutputs = it } != null) {
      try {
        val elapsed = it["__elapsed"]!!.toDouble()
    which doesn’t work because
    it
    can be null, and
    serviceOutputs
    can’t be null. I can correct this to:
    var serviceOutputs: Map<String, String>?
    while (resultReader.read(*header).also { serviceOutputs = it } != null) {
        serviceOutputs?.let {
          try {
            val elapsed = it["__elapsed"]!!.toDouble()
    but that is pretty messy and not indicative at all of what is happening.
    serviceOutputs
    can never be null in the block, and using a
    let
    is messy. Any way to accomplish this a bit cleaner?
    ✅ 1
    n
    n
    • 3
    • 26
  • a

    Animesh Sahu

    10/06/2020, 5:02 AM
    Is this a bug? E is not recognised as Int for example below
    d
    • 2
    • 1
  • t

    Timur Atakishiev

    10/06/2020, 7:41 AM
    Hi guys, is it possible to get type from Any? I need to check whether Any is Collection<String>. I tried something like
    inline fun <reified T> isTypeOf(any: Any?): Boolean {
        return any is T
    }
    
    val isTypeOf: Boolean = isTypeOf<Collection<String>>(Any)
    my Any is ArrayList of String.
    d
    v
    • 3
    • 14
  • a

    Andrew Gazelka

    10/06/2020, 8:47 AM
    iyo is doing something like this bad practice? (using KMongo here but it really doesn’t matter)… I just feel there should be some abstraction layer between mongo and the app, but building the abstraction layer usually is just a matter of writing brain-dead code
    t
    • 2
    • 1
  • j

    janvladimirmostert

    10/06/2020, 10:01 AM
    Is there a way to enforce curly braces for if statements and loops in Kotlin, or even better, automatically add it (like the code formatter in Ktlint does)? I noticed there are options in
    .editorconfig
    but it doesn't seem to do anything
    ij_any_if_brace_force = always
    ij_any_for_brace_force = always
    Ktlint seems to have such options, but it's marked as experimental and it will only show warnings What are other teams using for automated code formatting in Kotlin?
    👍 1
    s
    • 2
    • 6
  • j

    Jordi Pradel

    10/06/2020, 1:20 PM
    Hi everybody!! Acording to the documentation,
    async()
    exposes users to exceptions:
    Coroutine builders come in two flavors: propagating exceptions automatically (launch and actor) or exposing them to users (async and produce).
    But then, I'd expect wrarping the
    await()
    call in
    try... catch
    would just allow me to catch the exception produced in the
    async
    block. Instead, it seems the
    async()
    block's exception is handled by the supervisor. That gives me an odd behavior in this example:
    import kotlinx.coroutines.*
    fun main() = runBlocking<Unit> {
        try {
            val res = async {
              // suspend fun that ends up throwing ArithmeticException
              failedConcurrentSum()
            }
            res.await()
        } catch(e: ArithmeticException) {
            println("Computation failed with ArithmeticException")
        }
    }
    The odd part is that the exception is caught by
    catch
    but, at the same time, it is thrown by runBloking. See an executable snippet here: https://pl.kotl.in/sWjfVuEDr. Why is that so? What am I missing here??
    b
    • 2
    • 18
  • k

    kevinherron

    10/06/2020, 2:18 PM
    does dokka not have any support for something like <pre> or an equivalent that would preserve formatting/linebreaks?
    l
    • 2
    • 2
  • n

    Nir

    10/06/2020, 3:59 PM
    inline fun <T, K, R> Grouping<T, K>.fold(
        initialValueSelector: (key: K, element: T) -> R,
        operation: (key: K, accumulator: R, element: T) -> R
    ): Map<K, R>
    Semi related but the relationship between
    aggregate
    and
    fold
    for
    Grouping
    seems kind of fuzzy to me. It seems like this version of
    fold
    is just an awkward, two lambda version of aggregate. But then, the simplest case is handled most nicely by the
    fold
    overload taking a simple initial value. So the useful functionality is kind of spread between them, and yet aggregate is missing the most useful overload (IMHO). Just curious if there are reasons I'm missing why the API is this way. The first time I went to use
    Grouping
    it felt a bit clunkier than I'm used to in Kotlin.
    t
    • 2
    • 6
  • p

    Philipp Mayer

    10/06/2020, 7:24 PM
    Hello everyone, the compiler forced me to add an else branch in the following snippet. What's the reason behind that?
    return when ((1..2).random()) {
                1 -> "ABC"
                2 -> "XYZ"
                else -> "???"
            }
    The range only includes 1 and 2 and random returns an int.. 🤔
    d
    j
    r
    • 4
    • 3
  • k

    Karlo Lozovina

    10/06/2020, 7:28 PM
    If I have a base class with few hundred fields (basically constants, but not declared as static) will the derived classes also have hundreds of fields in memory? or will the JVM somehow optimize that?
    d
    s
    • 3
    • 11
  • p

    Philipp Mayer

    10/07/2020, 6:29 AM
    What's a good use case for an observable delegate? I digged into it and I can't really find a good example where I would defintly choose this one over anything else. I'm a backend guy. A quick look at google suggests that it seems to be more of an android thing? I came up with the topic while preparing a little kotlin intro for our Java devs, and thought that I could also show the builtin delegates.
    j
    • 2
    • 4
  • a

    Animesh Sahu

    10/07/2020, 1:47 PM
    Since the Generic information is present at the compile time, is it possible to access the generic type(s) of an object using the contracts, or any plans in the future?
    j
    • 2
    • 1
  • a

    Alex

    10/08/2020, 12:07 PM
    Is there a dedicated support channel for Kotlin?
    v
    k
    • 3
    • 5
Powered by Linen
Title
a

Alex

10/08/2020, 12:07 PM
Is there a dedicated support channel for Kotlin?
v

Vampire

10/08/2020, 12:07 PM
The whole server is about Kotlin
👍 1
a

Alex

10/08/2020, 12:08 PM
Yeah, I understand that. 🙂 Some communities have dedicated help channels, hence why I'm asking.
v

Vampire

10/08/2020, 12:10 PM
There are 469 channels, pick the one that matches your topic and look at the subject. For general Kotlin help, #general should be fine.
a

Alex

10/08/2020, 12:10 PM
Thanks! 🙂
k

kqr

10/08/2020, 4:10 PM
#getting-started maybe
View count: 2