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

    jimn

    07/21/2020, 5:38 AM
    I have an abstraction which amounts to Pair<Int,(Int)->Any?> this gets my needs met, however, there appears to be a JVM Integer boxing detour when the abstraction starts to nest; so the questions i have: 1. is this due to type erasure and/or generics forcing an object base class? 2. does th llvm compilation do a better job with LTO to eliminate boxing?
    f
    • 2
    • 3
  • n

    Nikky

    07/21/2020, 7:49 AM
    how does intellij idea know that the string in
    ".*".toRegex()
    is regex and marks the string as such so that highlighting works? is this something i can define on a function wit the right annotations? ps: lees like
    @Language("LANGUAGE_ID")
    works on preoperties.. sadly not on extension properties or extension functions it seems either way jsonpath is not in the list of supported things but this should still be very useful later
    t
    a
    • 3
    • 2
  • r

    Rob Murdock

    07/21/2020, 2:00 PM
    I guess this is an IDEA question - in a kotlin live templates, how does one include an import that references a receiver function? Normally the rule is use the fully qualified classname in the code and the editor converts that to imports automatically, but for the life of me I can’t figure out how to fully qualify a receiver function
    m
    • 2
    • 2
  • p

    pp.amorim

    07/21/2020, 5:13 PM
    Hi, I am getting this error:
    e: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Failed to generate expression: KtProperty
    In the code below:
    private val foo: Foo = object: Foo() {
    
        override fun bar(results: Results) {
            val results: List<Zed>? = safeCast(results.values)
        }
    
        private inline fun<reified T> safeCast(values: Any): List<T>? =
            (values as? List<*>)?.filterIsInstance<T>()
    }
    Is that because the
    inline fun
    inside the
    object
    ?
    Foo
    is a Java
    abstract class
    a
    • 2
    • 2
  • m

    Mina Makram

    07/21/2020, 8:45 PM
    Hello 😁😁 I have a question concerning the kotlin multiplatform, should I post it here or which channel?
    s
    • 2
    • 3
  • z

    z3ntu

    07/22/2020, 2:03 PM
    Hi, am I doing something wrong with this or is this a Kotlin bug?
    abstract class TestClass(open val value: Any)
    class TestClass2(override val value: UInt) : TestClass(value)
    
    val instance = TestClass2(0x1234u)
    println("value: ${instance.value}")
    I'm getting this exception:
    java.lang.ClassCastException: java.lang.Integer cannot be cast to kotlin.UInt
    	at Scratch_1$TestClass2.getValue(scratch_1.kts:2)
    	at Scratch_1.<init>(scratch_1.kts:5)
    w
    t
    r
    • 4
    • 7
  • s

    Sean Najera

    07/22/2020, 4:19 PM
    👋 does anyone know of a linter that would fail the build if classes/methods/fields were not documented with Kdoc comments?
    p
    • 2
    • 1
  • m

    Marc Knaup

    07/22/2020, 4:54 PM
    What Kotlin technologies and frameworks is JetBrains Space based on? Is it really already possible to build a large web project in Kotlin without going nuts? 😁 (The more I use JS/TS & React/Vue/Angular the more I’m going crazy…)
    s
    b
    r
    • 4
    • 101
  • p

    pp.amorim

    07/22/2020, 5:59 PM
    I am trying to test a function where it uses
    List.take(n)
    and I setup the
    iterator
    of the mocked list and populated it. I thought it could be enough, but I am getting NPE.
    `when`(mockedList.iterator()).thenReturn(list.iterator())
    I noticed that
    take
    creates a new arraylist by doing
    val list = ArrayList<T>(n)
    . could be the problem here?
    n
    t
    • 3
    • 12
  • t

    TwoClocks

    07/22/2020, 6:04 PM
    I want a function to take a
    KClass
    that extends a sealed class. Is there anyway to specify this at compile-time, or is this a run-time check?
    s
    j
    n
    • 4
    • 14
  • p

    pp.amorim

    07/22/2020, 8:10 PM
    Hi, how this answer could work with Kotlin? I tried with Consumer but it’s not being called. https://stackoverflow.com/a/49407513/2430555
    t
    j
    • 3
    • 27
  • m

    Marshall

    07/23/2020, 4:27 PM
    Any suggestions on how to apply a set of checks to a data model? My first thoughts are to define various checks like this:
    interface ErrorCheck<T> {
        fun isValid(item: T): Boolean
    }
    
    class PropertyRangeCheck<T, R : Comparable<R>>(val prop: KProperty1<T, R>, val range: ClosedRange<R>) : ErrorCheck<T> {
        override fun isValid(item: T) = range.contains(prop.get(item))
    }
    
    class PropertyStringLengthCheck<T>(val prop: KProperty1<T, String>, val range: IntRange) : ErrorCheck<T>{
        override fun isValid(item: T) = range.contains(prop.get(item).length)
    }
    p
    j
    • 3
    • 9
  • a

    Alberto

    07/23/2020, 4:33 PM
    what is the recommended project setup for a Kotlin Multiplatform library using Android Studio IDE?
    s
    j
    • 3
    • 6
  • n

    Nir

    07/23/2020, 6:09 PM
    I noticed that Kotlin zip only really operates on two sequences, compared to say python's zip which conveniently works on more than 2. How would you zip multiple sequences without nesting the result deeper and deeper? This sort of thing makes me scratch my head a bit on why tuples were removed from the language.
    b
    m
    s
    • 4
    • 55
  • j

    Jim

    07/23/2020, 9:21 PM
    Hey there, I've got a kotlin library that I'd like to use from a java project. Is there a way I can prevent needing to import kotlin-bom and apply the kotlin plugin to the java project's gradle file?
    m
    • 2
    • 3
  • t

    TwoClocks

    07/23/2020, 11:34 PM
    For Enum definition : Is there a way to specify the ordinal value of the types? Or do you just get what the compiler decides?
    n
    s
    t
    • 4
    • 4
  • t

    TwoClocks

    07/24/2020, 12:09 AM
    why does this compile :
    listOf(1,2,3,4).fold("") { acc, i -> acc }
    but this doesn't
    listOf(1,2,3,4).fold("") { acc, i -> { acc } }
    Or put another way : How do I write fold that is multi-statements and has some variables?
    r
    e
    • 3
    • 4
  • t

    TwoClocks

    07/24/2020, 5:17 AM
    how do I get gradle to depend on a local project that isn't in a subdirectory of the current project? I keep getting the error "could not be found in root project of...."
    h
    • 2
    • 14
  • a

    Andrew Gazelka

    07/24/2020, 6:30 AM
    This isn’t a Kotlin-specific question per-say, but I am doing this in kotlin. I’m trying to get away from extending classes because of intertwining behavior. I am abstracting my question, so if you want more specific details, ask me. I have a
    GUI
    which groups together `GUIComponent`s. Each
    GUI
    has a
    onExit()
    method that is called when the user tries to exit the
    GUI
    . • suppose I have
    GUI
    with a
    counter
    and every time a user
    GUIComponent
    is (A) clicked or the (B) user exits a
    GUI
    the
    counter
    should be increased. Once
    counter
    reached a
    threshold
    ,
    AnEvent
    occurs how should I structure this? WAY 1 Right now I almost might think of having
    GUIWithCounter(val counter: Int) : BaseGUI(...)
    and each time (A | B) occurs we open
    GUIWithCounter(counter+1)
    • this hard because there is a lot of logic which goes into the creation of
    BaseGUI
    … therefore, when creating it we’d want to use a factory method instead. In Kotlin, we can’t extend a class by using factory methods WAY 2 We could have
    GUIWithCounter : GUI
    (here
    GUI
    is an interface) … we’d create an instance of
    BaseGUI
    with factory methods with desired arguments… and then use strategy pattern (delegate
    GUI
    methods to the instance of
    BaseGUI
    ) .. this seems nice and dandy but here we’d need
    BaseGUI
    to be a concrete class. Therefore, we’d need a
    onExit()
    function in
    BaseGUI
    that does nothing/throws
    UnimplementedException
    (probably not an issue… but this is obv bad code. Perhaps
    BaseGUI
    would instead take a
    GUIEventHandler
    interface in the constructor and delegate
    onExit()
    to implementation defined there. Maybe just me but handlers seem like they could get messy with a bunch of
    object: …
    in code.) WAY 3 I don’t think this is a good idea???… but we could also have a
    GUICounterState
    and have a function which creates a
    BaseGUI
    with a handler and components that increment the
    GUICounterState
    . The
    GUICounterState
    would then have a detection method to see when
    counter
    has gone over a specific threshold. Thoughts?
    h
    j
    • 3
    • 26
  • a

    Alberto

    07/24/2020, 3:38 PM
    Is reflection handled differently between Android and iOS with Kotlin Multiplatform? Accessing the 'constructors' val from KClass returns "Unresolved reference: constructors" when building the iOS variant, but doesn't complain for the Android variant. I've tried also adding the reflect dependency in case.
    • 1
    • 1
  • p

    Pacane

    07/24/2020, 4:06 PM
    Does anyone know of a kotlin library that lets you do interactive CLI apps? I'd like something that wraps the logic of asking questions / parsing stdin, etc.
    z
    c
    +2
    • 5
    • 8
  • b

    bbaldino

    07/24/2020, 5:35 PM
    I have a method with a generic type
    T
    bounded by
    Any
    and call a method which returns a
    T
    , but in this case
    T
    is a java type (an enum) and the method (defined in java) returns null. I expected an exception to be thrown here, but instead the value of null trickles up just fine, and a (kotlin) method which is set to return a value
    T : Any
    ends up happily returning null. Is it expected that this won't throw somewhere? Is this just a limitation of interacting with Java types from kotlin?
    s
    • 2
    • 12
  • m

    Manuel Pérez Alcolea

    07/24/2020, 6:06 PM
    I'm trying to do something with Kotlin just for the sake of learning (and not for practical reasons). What I thought was: I want to see if I can have some sort of class built with mixins in Kotlin. That's not possible per-se since there's no multiple inheritance or any specific tool that allows it, but I tried to have a similar effect with delegates, knowing that
    by
    exists. So, my idea was to have, for example, something like this...
    s
    • 2
    • 24
  • j

    Joshy Josh

    07/24/2020, 10:17 PM
    I’m still learning generics in general, trying to implement a generic builder pattern for the type safe builder approach. I currently have… `
    fun <T> screen(init: T.() -> Unit): T = init as T
    Then eventually extend it have bounds, but for now. I keep getting a casting error. I’m assuming because it’s not invoking init, but I can’t seem to figure that part out.
    j
    • 2
    • 6
  • m

    Marc Knaup

    07/25/2020, 9:56 AM
    Why is this internal?
    someLong.toIntOrNull()
    would be nice if the value is out of range
    e
    • 2
    • 2
  • a

    ahmad abas

    07/25/2020, 10:32 AM
    What is the
    swiftUI
    of kotlin for android
    c
    m
    • 3
    • 2
  • d

    df

    07/25/2020, 6:07 PM
    data class Dummy(val namespace: String, val key: String, val value: String)
    val dummies = listOf(...)
    
    // do sth. with dummies
    
    // expected: Map<String (namespace), Map<String (key), String (value)>>
    r
    f
    • 3
    • 4
  • j

    jeggy

    07/25/2020, 8:11 PM
    val data: Map<Int, Pair<String, String>> = mapOf(
        25 to ("Hello" to "World")
    )
    
    data.map { (num: Int, (hello: String, world: String)) ->
        // ...
    }
    How come something like this is not valid code?
    a
    • 2
    • 1
  • a

    andylamax

    07/26/2020, 6:09 AM
    I don't know if this is the right place to ask this but here we go. Can someone deeply explain to me the difference between
    listOf<T>()
    and
    arrayListOf<T>
    . And while we are at it I would like to know more about the differences of 1.
    setOf<T>()
    and
    hashSetOf<T>()
    and
    linkedSetOf<T>()
    2.
    mapOf<T>()
    and
    hashMapOf<T>()
    and
    linkedMapOf<T>()
    Also why,
    List<T>
    has no factory methods called
    linkedListOf<T>()
    j
    r
    +2
    • 5
    • 17
  • m

    Mehdi Haghgoo

    07/26/2020, 10:44 AM
    In a kotlin code for Compose I saw a usage like this:
    val (a, b) = fun{}
    Could someone tell me please what this usage is? Is this an assignment? Why is this crazy usage even legal? Sorry I know Kotlin is great but it sometimes make me feel stupid 😞
    m
    d
    +2
    • 5
    • 8
Powered by Linen
Title
m

Mehdi Haghgoo

07/26/2020, 10:44 AM
In a kotlin code for Compose I saw a usage like this:
val (a, b) = fun{}
Could someone tell me please what this usage is? Is this an assignment? Why is this crazy usage even legal? Sorry I know Kotlin is great but it sometimes make me feel stupid 😞
m

Milan Hruban

07/26/2020, 10:50 AM
it's descructuring variable declaration, you can read about it here - https://kotlinlang.org/docs/reference/multi-declarations.html
❤️ 2
d

David Hernando

07/26/2020, 11:01 AM
as Milan said it is destructuring the result of
state { DrawerState.Closed }
see https://developer.android.com/reference/kotlin/androidx/compose/package-summary#state it grabs the type of the return in the init lambda
❤️ 1
here you can see that MutableState has 2 components which end up being the destructured variables https://developer.android.com/reference/kotlin/androidx/compose/MutableState
❤️ 1
a

andylamax

07/26/2020, 11:05 AM
The function does return a variable that can be destructured, and the coder destructures it right away without extracting the returned variable into another variable. It makes the code concise, but I do agree with you, It can sometimes be hard to read.
❤️ 1
m

Mehdi Haghgoo

07/26/2020, 1:16 PM
Does this have anything to do with inline functions? I have a hard time understanding Kotlin docs on inline functions.
d

David Hernando

07/26/2020, 2:39 PM
no, the inline keyword is used to tell the kotlin compiler to embed the code of the function instead of creating an object for it
❤️ 1
so if the function is used multiple times, the code is magically copypasted by the compiler, avoiding stack allocations and everything needed to call an extra function
❤️ 1
b

brandonmcansh

07/26/2020, 9:08 PM
Just to reiterate what Milan and David said, as long as the target implements componentN() interfaces you can destructure it.
View count: 2