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

    Néstor Díazgranados

    02/15/2021, 7:42 PM
    Hi everyone! I have a strange behavior which i consider should not be happening, but any insight is welcome. Basically i have some interfaces: interface A, B, C. (Inherits from B and C) interface B (with some methods) interface C (with some methods) at some point in code i ask a class implementing interface A :
    if ( class is B)
    but it is returning false
    n
    r
    • 3
    • 5
  • b

    Bilel El Oud

    02/15/2021, 8:41 PM
    Hi everyone, i am new and i started reading the language programming kotlin so i want to know how i can read Android with kotlin (the courses to read ...) Thanks for all 😃
    n
    • 2
    • 2
  • i

    igor.wojda

    02/15/2021, 11:16 PM
    Why I have “Unsafe use” here 🤔
    a
    g
    • 3
    • 2
  • i

    igor.wojda

    02/15/2021, 11:26 PM
    👉 I am doing a poll regarding testing frameworks usage in Kotlin projects. I m curious what is community preference, so please drop your vote here: https://twitter.com/igorwojda/status/1361303356484898821
    v
    • 2
    • 3
  • l

    Lewis Diamond

    02/16/2021, 12:56 AM
    Is there a Flow interface to stdin?
    ☝️ 1
    z
    • 2
    • 6
  • c

    Cicero

    02/16/2021, 9:18 AM
    Hey people, I have a “when” question. When faced with this a colleague of mine recommended a one line refactor but I can’t achieve it because.
    fun fillFieldsForAttribute(attribute: Map<String, Any>): Any? {
        when (localVariable) {
            is TruParameter -> {
                localVariable.update(attribute)
            }
            is TruVoltage -> {
                localVariable.update(attribute)
            }
            is TruBatteryState -> {
                localVariable.update(attribute)
            }
        }
        return localVariable
    }
    The classes referenced after “is” are all a subclass of “TruAbstract” which contains “update” what I tried was
    (localVariable as TruAbstract).update(attribute)
    return localVariable
    and this does not work Do you see any good idea for a refactor here?
    g
    • 2
    • 13
  • b

    Big Chungus

    02/16/2021, 11:03 AM
    Are there any plans for union types in Kotlin or at least KotlinJS? I heard mentions in one if the arrow meta talks that kotlin already supports union types, just doesn't expose them to public api. Curious to know why
    c
    e
    • 3
    • 2
  • s

    Sinan Gunes

    02/16/2021, 11:56 AM
    feels like Spam ----vvv
    m
    • 2
    • 2
  • m

    mending3

    02/16/2021, 12:53 PM
    intellij why does
    getResource
    give me null? I have a
    .txt
    file in the same directory with
    MyClass.java
    I print the class with this code
    println(MyClass::class.java)
    it returns me
    class com.myapp.vendors.lib.MyClass
    However when I want to get the txt file with this code:
    println(MyClass::class.java.getResource("my.txt"))
    it returns me null
    e
    m
    • 3
    • 4
  • m

    Marc Knaup

    02/16/2021, 5:22 PM
    This class can only be used with the compiler argument ‘-Xopt-in=kotlin.RequiresOptIn’
    What is this warning for? I can use the class just fine even without that arguments 🤔 I guess the message is just misleading.
    r
    • 2
    • 3
  • o

    OG

    02/16/2021, 5:28 PM
    Hello everyone 👋 I'm trying to help a colleague of mine get access to this slack workspace, it seems the invite option has been disabled for me. Can someone please help point me in the right direction or offer some guidance on how they can get invited/access to this slack workspace?
    c
    • 2
    • 2
  • d

    Devin Fee

    02/16/2021, 7:47 PM
    what is the impact of setting
    kotlinOptions.jvmTarget
    to
    JavaVersion.VERSION_1_8
    or
    JavaVersion.VERSION_15
    – assuming i’m using Java 15? • (1.4.20 release notes where support for 15 was added) • (jvmTarget documentation) will my code run in an optimized manner – as it can take advantage of newer JDK features, etc?
    e
    • 2
    • 8
  • m

    Marc Knaup

    02/16/2021, 9:11 PM
    I really miss union types. Or simpler error handling.
    User | UserNotFound | NetworkError
    instead of a dozen sealed classes all defining the same errors over and over again.
    ➕ 9
    e
    n
    h
    • 4
    • 34
  • k

    Kirill Grouchnikov

    02/16/2021, 10:47 PM
    Still no 1.4.30 stable plugin for IDEA?
    m
    • 2
    • 8
  • n

    nkiesel

    02/16/2021, 11:52 PM
    What is a better way than
    val port = property.getProperty("notification.port").orEmpty().let { if (it.isNotBlank()) it else "7100"}
    ? Is there something like ``val port = firstContent(property.getProperty("notification.port"), "7100")` ?
    i
    s
    +2
    • 5
    • 11
  • i

    igor.wojda

    02/17/2021, 7:58 AM
    Is it possible to make all items (classes/objects/interfaces/enums…) in the module
    internal
    by default?
    y
    • 2
    • 1
  • d

    Denis

    02/17/2021, 6:17 PM
    It looks like Kotlin docs layout has been updated and now it's "impossible" to google "kotlin when expression" and find the right page. It only gives a spec page https://kotlinlang.org/spec/expressions.html.
    n
    e
    • 3
    • 2
  • d

    Denis

    02/17/2021, 6:28 PM
    I have 2 questions wrt sealed classes and `when`:
    sealed class A {
        data class X(val m: Int) : A()
        data class Y(val m: Int) : A()
        data class Z(val m: Int) : A()
    }
    val x = when (val a: A = A.X(3)) {
        is A.X, is A.Y -> a.m  // <<<<<<<<<<
        is A.Z -> a.m
    }
    1. Why does Android Studio say
    'when' expression must be exhaustive, add necessary 'else' branch
    ? Aren't all cases covered here? 2. Why is
    a.m
    no accessible on the marked line? It says
    Unresolved reference: m
    .
    m
    n
    e
    • 4
    • 19
  • d

    Denis

    02/17/2021, 8:00 PM
    (Using the sealed class from the previous message) Is there a reason IDE doesn't suggest eliminating
    when
    altogether in this case?
    val x: A = A.X(0)
    when (x) {
        else -> 1
    }
    n
    e
    • 3
    • 6
  • k

    Kuba Petržílka

    02/17/2021, 8:14 PM
    Maybe stupid question, but I m wondering one thing - is it smart to create a box for specialized array type in order to avoid having to override the
    equals()
    methods in each and every data class when I want to use one of these? 🤔 If so why such comparable variants of the spec. array types are not part of the STL yet? Obviously, I cannot use all the exension methods provided by the STL directly then.. but it still feels a bit better than messing up my domain model with all those overrides of equals() and hashCode() typically because of one single array field.. Something like this:
    class ComparableByteArray (val array: ByteArray) {
        val size: Int
            get() = array.size
    
        constructor(size: Int) : this(ByteArray(size))
        constructor(other: ComparableByteArray) : this(other.array.copyOf())
    
        override fun equals(other: Any?): Boolean =
            (this === other) || (javaClass == other?.javaClass && array.contentEquals((other as ComparableByteArray).array))
        override fun hashCode(): Int = array.contentHashCode()
        override fun toString(): String = array.toString()
        operator fun get(index: Int) = array[index]
        operator fun set(index: Int, value: Byte) = array.set(index, value)
        operator fun iterator(): ByteIterator = array.iterator()
    }
    
    data class User {
       //....,
       secretKey: ComparableByteArray
       //...,
    
       // <-- Would have to override equals() and hashCode() here if I used just ByteArray so the data class loses its purpose
    }
    r
    m
    m
    • 4
    • 7
  • a

    antonkeks

    02/17/2021, 9:19 PM
    Why <*> generics are casted to Nothing by the compiler instead of Any?, e.g. why can't I implement such a function without unchecked casts?
    fun <T: Any> T.toValuesSkipping(vararg skip: KProperty1<T, *>): Map<String, Any?> =
      (this::class.memberProperties - skip)
      .filter { it.javaField != null }.map { it.name to it.get(this) }.toMap()
    r
    m
    e
    • 4
    • 16
  • d

    Dariusz Kuc

    02/17/2021, 9:55 PM
    ugh.... 😢 why this doesn't work
    class Wrapper {
        sealed class Whatever {
            abstract val name: String
        }
    
        data class First(override val name: String, val first: String) : Whatever() // constructor is private....
    }
    m
    n
    d
    • 4
    • 5
  • g

    Gyu hyeon Lee

    02/18/2021, 7:17 PM
    Spent a whole day on the error "Class A cannot be cast to Class A" when trying to access
    @Cacheable
    method return value when it clearly should be working since I literally just put the same class instance into the cache when I called the method for the first time 1 second ago... Couldn't find a single article that helped me on the issue.
    mvn clean
    didn't help either. ... It worked after I invalidated intellij cache and restarted IDE. I love my life sometimes.
    🚔 1
    🥴 1
    ➖ 2
    n
    • 2
    • 1
  • f

    Fabio

    02/18/2021, 10:06 PM
    I'm looking for some wisdom on writing Kotlin libraries, specifically for Android in my case, specifically for helping write the couple of apps that I support. Sometimes I feel like it's too hard to balance what goes in the library and what goes in the app, or the libraries are too small and not worth it. Any tips?
    ➖ 1
    b
    n
    m
    • 4
    • 9
  • b

    bodiam

    02/18/2021, 11:23 PM
    Hi all, I’ve got quite some pieces of code in my application like this:
    val product: Product = products.find { it.name = input } ?: throw IllegalArgumentException("Product $input not found")
    I know that it will be very unlikely to not find the product in this list (say, impossible), so, I’d rather not clutter my code with the “if null throw exception” stuff, and rather have
    find
    throw an exception if the product can’t be found, like this:
    val product: Product = products.find { it.name = input }
    I’d rather not make Product nullable (
    Product?
    ), cause that will lead to some if/then elses later in my code. Is there any clean way I’ve missed to accomplish this?
    ‼️ 4
    y
    n
    +2
    • 5
    • 9
  • m

    Manuel Pérez Alcolea

    02/19/2021, 5:16 AM
    I'm trying to run a .class file compiled through Gradle, just for the sake of it but I haven't had any success. I want to use
    java
    , how can I make it run? I've tried stuff like this:
    $ java -cp "/usr/share/kotlin/lib/kotlin-stdlib.jar:." kott.AppKt     
    Error: Could not find or load main class kott.AppKt
    Caused by: java.lang.ClassNotFoundException: kott.AppKt
    
    $ java AppKt 
    Error: Could not find or load main class AppKt
    Caused by: java.lang.NoClassDefFoundError: kott/AppKt (wrong name: AppKt)
    e
    a
    • 3
    • 26
  • s

    Slackbot

    02/19/2021, 8:36 AM
    This message was deleted.
    a
    • 2
    • 1
  • j

    James Richardson

    02/19/2021, 8:46 AM
    It very much depends on your software development and runtime constraints. What factors are important or critical for you?
    :thread-please: 3
    n
    • 2
    • 2
  • v

    Victor Ermolaev

    02/19/2021, 10:44 AM
    Hi there, I am developing a binary serialization with kotlinx.serialization framework. I am currently stuck with serializing public keys (likely because it is an interface). The issue is that I can always serialize a public key, but to deserialize I need to know what kind of key this is. I did achieve such functionality using surrogates (as in docs) in simple cases such as
    class User(val id: PublicKey)
    but it does fail with generics
    class<T> User(val id: T)
    . I get
    Class 'RSAPublicKeyImpl' is not registered for polymorphic serialization in the scope of 'PublicKey'.
    when I insert a public key instance there. My minimally working example is here https://github.com/vnermolaev/serde Does anyone have experience with kotlinx.serialization and applying it together with generics?
    j
    • 2
    • 2
  • s

    stephanmg

    02/19/2021, 10:45 AM
    hi, quick question: I do have compiled a kotlin project to a jar file. now I want to pass parameters, I do so java -jar bg.jar --angle 2. However java -jar bg.jar --angle '-2' does not work.
    c
    • 2
    • 29
Powered by Linen
Title
s

stephanmg

02/19/2021, 10:45 AM
hi, quick question: I do have compiled a kotlin project to a jar file. now I want to pass parameters, I do so java -jar bg.jar --angle 2. However java -jar bg.jar --angle '-2' does not work.
Exception in thread "main" java.lang.IllegalStateException: Missing value for CLI argument --angle
probably not related to Kotlin, I apologize, but maybe somebody can hint how to do this? I seem right now I can't wrap my head around this triviality.
thanks!
c

Cicero

02/19/2021, 11:00 AM
sorry for the quick gun jump here but it seems the parameter is not being recognized, maybe it’s not a string value?
s

stephanmg

02/19/2021, 11:16 AM
yeah you are right, it's not a string value. so I need negative numbers, should I make this angle parameter a string param? then parse teh double
@Cicero oh well that's my own code, never mind. lol. 🙂 found the problem
🎉 1
for some reason I had weird custom command line argument parsing in my code
there are option parsers for kotlin, right? so I don't have to do this.
guess that was pretty old code
well i mean in the standard library
c

Cicero

02/19/2021, 11:59 AM
😅 I’m happy to help?
s

stephanmg

02/19/2021, 12:22 PM
What I meant was: Is there a standard way to handle commadn line arguments in Kotlin.
like a standard argument parsing library
c

Cicero

02/19/2021, 12:23 PM
Do I understand it’s something “like this”: Reading a name from the command line | Try Kotlin (kotlinlang.org)
Or this one Kotlin command-line compiler—Kotlin (kotlinlang.org)
s

stephanmg

02/19/2021, 12:24 PM
yeah i thought about using https://github.com/Kotlin/kotlinx-cli
but I didn't want to include any non-standard dependencies into the project actually
standard librry dependencies
c

Cicero

02/19/2021, 12:27 PM
I know what you mean but this library tells me something like you would need to use it
When you find this kind of thing inside of the Kotlin repo, then it’s kind of unavoidable
s

stephanmg

02/19/2021, 12:28 PM
then there is https://www.kotlinresources.com/library/kotlin-argparser/
I'm just baffeld what to use.
for now I'm using a little code to manage CLI arguments myself
so no additional library needed
c

Cicero

02/19/2021, 12:30 PM
Cool, but I would go with Kotlin repo solution always, even then argparser looks fancier.
s

stephanmg

02/19/2021, 12:31 PM
What is Kotlin repo solution?
c

Cicero

02/19/2021, 12:47 PM
https://github.com/Kotlin/kotlinx-cli -> Kotlin source https://www.kotlinresources.com/library/kotlin-argparser/ -> xenomachina
s

stephanmg

02/19/2021, 1:54 PM
i see
thanks
View count: 1