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

    sikri

    11/26/2019, 10:43 AM
    tl;dr we cannot use spread operator with collections, even though SpreadBuilder supports collections and iterator under the neath. Will it change anywhen? For now, I have to write
    listOf(a, b, listOf(c, d).toTypedArray())
    Even though,
    SpreadBuilder.addSpread
    supports Collections and Iterators, based on this,
    public void addSpread(Object container) {
            ...
            else if (container instanceof Collection) {
                list.addAll((Collection) container);
            }
            else if (container instanceof Iterable) {
                for (Object element : (Iterable) container) {
                    list.add(element);
                }
            }
            ...
        }
    I cannot write code like this, even though it seems being supported:
    listOf(a, b, listOf(c,d))
    This leads to this in bytecode:
    L41
        LINENUMBER 154 L41
        ALOAD 15
        ICONST_0
        ANEWARRAY pl/some/type
        INVOKEINTERFACE java/util/Collection.toArray ([Ljava/lang/Object;)[Ljava/lang/Object; (itf)
       L43
        ASTORE 21
        ALOAD 13
        ALOAD 12
        ALOAD 21
        INVOKEVIRTUAL kotlin/jvm/internal/SpreadBuilder.addSpread (Ljava/lang/Object;)V
    And as you can see, there is a useless array copy
    d
    • 2
    • 3
  • e

    Eugen Martynov

    11/26/2019, 4:08 PM
    We are getting some strange error
    Execution failed for task ':common-i18n:compileDebugKotlin'.
    > java.util.ConcurrentModificationException (no error message)
    m
    c
    a
    • 4
    • 6
  • j

    Janelle Fullen

    11/26/2019, 10:16 PM
    Can someone help me with pulling in source dependencies via Gradle?
    i
    • 2
    • 7
  • u

    user

    11/27/2019, 7:28 AM
    message has been deleted
    t
    • 1
    • 1
  • v

    vpriscan

    11/27/2019, 9:41 AM
    Is it just me or Unit and UInt are too similar and too easy to misread
    d
    p
    +2
    • 5
    • 7
  • i

    Ive Vasiljevic

    11/27/2019, 3:54 PM
    What is the difference between:
    class SomeClass1(private val property: Application)
    and
    class SomeClass2() {
    
       private val property: Application? = null
    }
    I've noticed that in the second example of property declaration you HAVE to initialize property otherwise the compiler says that property needs to be abstract or initialized, but on the other hand in the first example initialization is optional.
    d
    j
    e
    • 4
    • 3
  • j

    Jay M

    11/28/2019, 11:03 AM
    can anybody please explain the meaning of the statement, val image = +imageResource(R.drawable.header) what is the use of "+" sign and hwy to use it?
    d
    d
    +2
    • 5
    • 13
  • m

    Maurice Jouvet

    11/28/2019, 12:43 PM
    Hi, is there a Kotlin Multiplatform group? I am building an app an Android/iOS and I want to have some help/insight.
    i
    c
    • 3
    • 3
  • j

    Jukka Siivonen

    11/28/2019, 3:16 PM
    Is there more cleaner way to achive something like this (template = Spring transaction template)
    transactionTemplate.execute {
                val bar = doSomethingTransactional()
                if (bar) {
                    { doSomethingOutsideTransaction(bar) }
                } else {
                    { doSomethingElseOutsideTransaction() }
                }
            }?.invoke()
    So that part of the code is run inside transaction and some part of code is run outside transaction (with data found inside transaction). Example is simplified a lot from real use case so bear with me.. :)
    m
    • 2
    • 8
  • d

    df

    11/28/2019, 4:00 PM
    Hey there. I have some data classes that don't have default values (because it doesn't make sense in the production enviroment) but I would like to have an easy way to create instances of those classes with default values in my unit / integration test. Right now I'm doing sth. like this
    fun createAddCartItemDto(
            partnerId: Long = 29L,
            productId: Long = 40L,
            productVariantLabel: String = "A1",
            testName: String? = null,
            bucketGroup: String? = null
    ) = AddCartItemDto(
            partnerId = partnerId,
            productId = productId,
            productVariantLabel = productVariantLabel,
            bucketGroup = bucketGroup,
            testName = testName
    )
    but i'm not the biggest fan of the duplicated parameter list .. better ideas?
    m
    g
    m
    • 4
    • 7
  • i

    Ive Vasiljevic

    11/28/2019, 4:16 PM
    Is Delegate pattern (Composition) actually favored over inheritance?
    s
    • 2
    • 2
  • j

    Jiri Bruchanov

    11/28/2019, 6:10 PM
    Hi, wondering if I can have anonymous/named extension function like following
    val x = fun Int.() { this.toString() }
    1.x()
    can be 'x' defined as anonymous/named extension property ? so I could have
    1.x
    ?
    👀 1
    m
    s
    • 3
    • 5
  • d

    Daniel

    11/28/2019, 7:05 PM
    Hi all, today at work we found something curious and I want to ask if this is the intended behaviour: Suppose we have a sealed class with a property. Then we have a data class inheriting from this selaed class:
    sealed class TestClassParent(val any: Any) {
        
        data class TestClassChild(val anyOther: Any) : TestClassParent(Any())
        
    }
    
    When I decompile this super.equals() seems to be not called in the TestClassChild:
    
    public boolean equals(@Nullable Object var1) {
             if (this != var1) {
                if (var1 instanceof TestClassParent.TestClassChild) {
                   TestClassParent.TestClassChild var2 = (TestClassParent.TestClassChild)var1;
                   if (Intrinsics.areEqual(this.anyOther, var2.anyOther)) {
                      return true;
                   }
                }
    
                return false;
             } else {
                return true;
             }
          }
    
    I don't know if you could construct a case where this matters, but at first glance it seems that the equals contract is broken
    s
    • 2
    • 1
  • d

    Daniel

    11/28/2019, 7:07 PM
    This also happens when the sealed class has a overwritten equals method, it does'nt seem to matter (I omitted it here)
    b
    • 2
    • 1
  • s

    Sylvain Patenaude

    11/28/2019, 9:04 PM
    Is there a "pure" Kotlin way to convert a UByteArray into a UTF-8 string? Thanks! Edit: If there's no built-in support for this, can I just convert my array (UByteArray -> ByteArray) and then call
    decodeToString
    on it?
    s
    e
    i
    • 4
    • 5
  • j

    Joey

    11/29/2019, 1:28 AM
    Does multiplatform library have the access to run background tasks for android and iOS? Sample use case is to monitor their location even app is in the background. Thanks in advance!
    b
    • 2
    • 4
  • s

    steenooo

    11/29/2019, 9:12 AM
    Is there a method in Stream that allows you to map and filter in one method? Fx cast x and ignore the entries that would fail the cast
    d
    • 2
    • 2
  • j

    Jaymin.Kim

    11/29/2019, 9:17 AM
    import kotlinx.coroutines.delay
    import kotlinx.coroutines.runBlocking
    
    fun main() = runBlocking {
        sequence {
            yield(10)
        }.map {
            foo() // ERROR: Suspension functions can be called only within coroutine body
        }
        Unit
    }
    
    suspend fun foo() = delay(1000L)
    why this is not possible?
    d
    • 2
    • 3
  • m

    molikuner

    11/29/2019, 9:53 AM
    Hey, could someone explain to me, why the following prints true?
    val a = "x"
    val b = "x"
    println(a === b)
    This differs from the behaviour that I expected, as the following prints false:
    val c = "X".toLowerCase()
    println(a === c)
    example code: https://pl.kotl.in/NTVgQNuWe
    k
    d
    d
    • 4
    • 6
  • s

    Simon Craigie

    11/29/2019, 4:55 PM
    hey all! Is there a way to create behaviour such as this without casting? I read that you can avoid unchecked cast exceptions with reified types but i can't seem to find a way to do this with function parameters:
    fun <PARENT, CHILD: PARENT> returnFuncWithParentTypeAsParameter(resolver: (CHILD) -> Unit): (PARENT) -> Unit {
                return resolver as (PARENT) -> Unit
            }
    Thanks in advance!
    a
    r
    • 3
    • 7
  • h

    Holger Steinhauer [Mod]

    11/29/2019, 5:04 PM
    Hmm, I hope you peops don’t mind me asking, but Slack behaves weirdly for this organisation. Every time I switch channels, the Channel Info sidebar on the right side opens. I couldn’t find any settings to disable that. All other Slack Orgs I use do not have this “feature”. Can anyone help me on getting this disabled on here as well?
    r
    • 2
    • 1
  • v

    ventura

    11/29/2019, 5:07 PM
    How do I create a
    kotlin.Result
    programatically?
    g
    l
    • 3
    • 4
  • n

    Nir

    11/29/2019, 6:36 PM
    In Kotlin, suppose I have two dataclasses that have some shared fields. In python dataclasses, I would solve this by factoring the shared fields into another dataclass, and then inheriting from both, and things like equality would work as expected. kotlin doesn't allow inheritance of dataclasses, so how would you solve this problem?
    y
    • 2
    • 3
  • m

    mikehearn

    11/29/2019, 6:39 PM
    but I'm not sure what you mean by work as expected here. you want
    a == b
    to pass when a and b are of different types and may have fields that aren't included in the comparison?
    :thread-please: 4
    n
    s
    b
    • 4
    • 63
  • s

    standinga

    11/29/2019, 7:13 PM
    does it make sense? or this is not the best approach? Thanks!
    k
    k
    c
    • 4
    • 11
  • g

    g4sarma

    11/29/2019, 7:51 PM
    Hi guys, do we have a channel for dependency injection specially koin ?
    a
    • 2
    • 2
  • i

    iex

    11/30/2019, 12:11 PM
    Hi! Is there a lang feature request somewhere for currying (out of the box)?
    k
    m
    • 3
    • 8
  • u

    ursus

    11/30/2019, 7:49 PM
    fun Message.diffUtilEquals(o: Any): Boolean {
        if (o !is Message) return false
        if (id != o.id) return false
        return true
    }
    
    fun TextMessage.diffUtilEquals(o: Any): Boolean {
        if (!super.diffUtilEquals(o)) return false
        if (o !is TextMessage) return false
        if (text != o.text) return false
        return true
    }
    n
    m
    • 3
    • 8
  • h

    Hullaballoonatic

    12/01/2019, 1:52 AM
    It's great that you can pass method references as arguments like so:
    operator fun Vector.times(scalar: Double) = mapToVector(scalar::times)
    but since division isn't commutative, i can't use the same syntax for that, unless there's a way I don't know of?
    operator fun Vector.div(divisor: Double) = mapToVector { it / divisor }
    d
    • 2
    • 1
  • m

    Marko Mitic

    12/01/2019, 3:00 PM
    Is there any quick way to "reverse" map, so make a
    Map<A, B>
    into
    Map<B, List<A>>
    ?
    e
    • 2
    • 2
Powered by Linen
Title
m

Marko Mitic

12/01/2019, 3:00 PM
Is there any quick way to "reverse" map, so make a
Map<A, B>
into
Map<B, List<A>>
?
Even better,
Map<A, List<B>>
into
Map<B, List<A>>
e

Egor Babarykin

12/01/2019, 3:31 PM
fun <A, B> Map<A, List<B>>.reverse(): Map<B, List<A>> = flatMap { it.value.map { v -> it.key to v } }
                    .groupBy({ it.second }, { it.first })
👍 2
View count: 32