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

    Travis Griggs

    03/15/2021, 7:20 PM
    syntax struggle, I have an enum class, which I want to return an appropriate FragmentActivity subtype:
    val activity:KClass<FragmentActivity>
       get() {
          return when (this) {
             Single, SingleWithSense, SingleWithPeriod, Dual, Echo -> AllocatedNodeActivity::class
             Central -> CentralNodeActivity::class
             Unknown -> PristineNodeActivity::class
          }
       }
    It just yells at me because none of the return types match the KClass<FragmentActivity> type. What's the secret sauce I'm missing?
    s
    • 2
    • 9
  • b

    bbaldino

    03/15/2021, 7:43 PM
    I’ve got a weird issue with, I think, the kotlin sdk version between intellij and maven. If I run my unit test from intellij (via the run configuration) it runs fine. If I run via maven (both from the command line and via the intelllij maven lifecycle actions) I get a complaint about, effectively, a smart-cast not working. In my pom.xml I have the kotlin version set to 1.3.72 and everywhere in project structure in intelllij seems to agree with that, but it looks like intellij’s is using another version. I would normally just ignore this, but if I try and change my code to not rely on the smart cast, intellij keeps warning me about “unnecessary cast” (and I have -werror enabled, so I can’t build with the warning). Where else can I check for a place where a version might be set incorrectly? I do know that the kotlinc plugin is 1.4.31, but I thought it should still be running “as” 1.3.71 if that’s set everywhere.
    e
    • 2
    • 15
  • t

    Travis Griggs

    03/15/2021, 10:20 PM
    Any reason that UByte can do bitwise AND, OR, XOR, but not SHIFT operations?
    c
    s
    e
    • 4
    • 7
  • t

    therealbluepandabear

    03/16/2021, 2:39 AM
    This is my current code to match a command:
    private fun extractCommand(command: String): Boolean {
        val asArr = command.split("\\s")
        if (asArr[0].equals(".attack", ignoreCase = true) && asArr.size == 3)
            return true
    }
    Is there a way to do this with regex? I think that's the best way
    t
    n
    e
    • 4
    • 8
  • s

    Slackbot

    03/16/2021, 3:37 PM
    This message was deleted.
    i
    d
    • 3
    • 5
  • b

    Benoît

    03/16/2021, 5:30 PM
    I'm getting this error even though my code compiles, I can even run my unit tests from the IDE. I'm using Android Studio 4.2 beta 6. I have another computer using the same version of AS and I don't get the error Any idea?
    l
    m
    • 3
    • 5
  • j

    jeggy

    03/16/2021, 5:49 PM
    data class MyType(
        /**
         * Information [testing...]
         */
        val field: String,
    )
    I'm not sure if I have found a Kotlin bug or it's supposed to do this? But this data class results in a compiler error because of the
    [testing...]
    comment.
    s
    c
    +2
    • 5
    • 20
  • t

    Travis Griggs

    03/16/2021, 6:45 PM
    Parameter 'whatever' is never used
    warnings for polymorphic methods, where in some cases, you really don't need to use the argument, but it's there for polymorphism. What's the idiomatic way to deal with this? I apparently cannot use `_`; I don't understand why.
    z
    c
    • 3
    • 2
  • t

    TwoClocks

    03/16/2021, 11:40 PM
    I can set class
    val
    in
    init
    or in a constructor, but not both? What's the reasoning behind this code not compiling? https://pl.kotl.in/lVxY8idN4
    n
    s
    c
    • 4
    • 25
  • f

    Fredrik Larsen

    03/17/2021, 10:12 AM
    Are there any known limitations to the visibility of extension functions on
    operator
    invoke? I’m having an issue where it’s only accessible within the same (gradle) module.
    operator fun Foo.invoke(block: FooDsl.() -> Unit) { ... }
    fun Bar.invoke(block: BarDsl.() -> Unit) { ... }
    I.e. the following does not work from another module
    foo { // cannot resolve
    }
    However, this does
    bar.invoke {
    }
    There are no declarations of invoke in the classes in question. And for completeness this also works from another module
    foo.invoke {
    }
    ✅ 1
    e
    • 2
    • 5
  • m

    melatonina

    03/17/2021, 12:29 PM
    Is it correct that, currently, we can't create inline classes that implement Comparable<T>?
    e
    • 2
    • 6
  • m

    melatonina

    03/17/2021, 5:35 PM
    @elizarov This is a MCVE for the problem mentioned in my previous message. Calling next() on A from this code:
    interface X<T> {
        operator fun plus(n: Int) : T
        fun next(): T = this + 1
    }
    
    inline class A(val value: Int) : X<A> {
        override operator fun plus(n: Int) = A(value + n)
    }
    causes
    Exception in thread "main" java.lang.ClassCastException: class com.example.A cannot be cast to class java.lang.Number (com.example.A is in unnamed module of loader 'app'; java.lang.Number is in module java.base of loader 'bootstrap')
    	at com.example.A.next-m5RZA0A(Example.kt:32)
    	at com.example.ExampleKt.test(Example.kt:5)
    This version causes the same exception:
    interface X<T> {
        fun add(n: Int) : T
        fun next(): T = add(1)
    }
    
    inline class A(val value: Int) : X<A> {
        override fun add(n: Int) = A(value + n)
    }
    This version is OK:
    interface X<T> {
        fun next(): T
    }
    
    inline class A(val value: Int) : X<A> {
        override fun next() =  A(value + 1)
    }
    This version is OK, too:
    interface X<T> {
        fun next(): T
    }
    
    inline class A(val value: Int) : X<A> {
        operator fun plus(n: Int) = A(value + n)
        override fun next() =  this + 1
    }
    Does it have anything to do with boxing? Is this because the plus operator is called on a reference of an interface? Is this something limited to mathematical operators? What should I do? Should I prefer code generation instead of interface implementation when using inline classes?
    r
    e
    • 3
    • 2
  • g

    Gerard Bosch

    03/17/2021, 6:38 PM
    Hi there! Does the following make sense? I'm totally new to Kotlin and just experimenting
    fun <T> T?.onNull(effects: () -> Unit): T? {
        if (this == null) effects()
        return this
    }
    What I feel strange is that by defining the above extension, I'm allowed to invoke it on
    non-nullable
    types, which results a little counter-intuitive. I mean, given the above I can do:
    val str: String = "helo"  // non-nullable type
    str.onNull { print("Will never print as I'm not actually null") }  // <-- Why the compiler allows this?
    Is it possible to restrict it just to nullables as in
    T?
    Thx 🙂
    m
    n
    +5
    • 8
    • 75
  • f

    Fábio Carneiro

    03/17/2021, 9:15 PM
    I noticed that two subtypes of a sealed class can be added to a Set with the same value. This is probably because Equals across different types will not return true. What would be the recommended approach to prevent same value, but different type of the same sealed class in a Set?
    n
    m
    e
    • 4
    • 223
  • t

    Travis Griggs

    03/17/2021, 11:32 PM
    Can I match on pairs of when values? I have a
    status
    and a
    newState
    values, and I'd like to match on combinations. I could of course nest them, but I was hoping to match on a tuple like thing... e.g. when (status, newState) { 42, 13 -> "The answer is bad luck" }
    n
    e
    • 3
    • 6
  • t

    therealbluepandabear

    03/18/2021, 3:41 AM
    Hi... I'm getting index out of bounds exception from this code. anyone know why?
    private var worldSize: Int = 0
    private var biomes: MutableMap<Biome, IntRange> = mutableMapOf()
    
    data class PointData(val currentPoint: Int?, val currentBiome: Biome)
    
    fun getPointData(point: Int): PointData {
        biomes.values.forEach {
            if (it.contains(point)) {
                return PointData(point, biomes.keys.elementAt(biomes.keys.indexOf(it)))
            }
        }
        return PointData(null, Savannah())
    }
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Collection doesn't contain element at index -1.
    e
    n
    • 3
    • 10
  • r

    Ragvax

    03/18/2021, 6:17 AM
    🙋‍♂️ Hi guys, I'm new around here! A quick question, can I post my stackoverflow question link in here? Or should i just put the whole question here?
    i
    • 2
    • 2
  • d

    Denis Sazonov

    03/18/2021, 10:42 AM
    Hi, could somebody help me here? Asked in #coroutines but nobody still help.
    e
    • 2
    • 2
  • j

    Jordan Foo

    03/18/2021, 3:19 PM
    Hi team! I understand what extension functions are, such as adding a newFunction
    fun Bar.newFunction() {}
    What exactly does this do?
    fun Bar.() {}
    m
    c
    z
    • 4
    • 15
  • t

    tim

    03/18/2021, 4:51 PM
    Hi everyone, I have a state management challenge in our system and I'd love to hear how others might be solving this today, or to hear recommendations on how we could approach it. Our architecture is micro services based and we use mongodb for persistence. For examples sake, lets say there is an
    AccountState
    object in one micro service. Now for the various use cases that act on this state all have narrowed attributes of the state they're interested in. For example, Login only cares about Username and Password, whereas Change Profile Details cares about the Name and Address fields. When I retrieve data from mongo, I'd like to use a projection to only return the fields needed in the running use case and then I'd like to de-serialise that projection into something where my use cases can access those values without being cluttered with every filed that on the complete state object. ie. i don't want to create a version of the state where every value is nullable / wrapped in an Option. In typescript I would use something along these lines:
    type State {
     const id: string
     const username: string
     const password: string
     const name: string
     const address: string[]
    }
    
    type NarrowViewOfState = Pick<State, "name", "address">
    But as kotlin doesn't offer the same type flexibility; has anyone had success here?
    n
    • 2
    • 21
  • p

    Petru

    03/18/2021, 4:52 PM
    Hello Q: Can we override the error messages from the FIR checker? In my case I have a private setter and would like to indicate to clients the supported way to update the value.
    d
    • 2
    • 7
  • c

    christophsturm

    03/18/2021, 5:43 PM
    does anyone here know the answer?
    q
    w
    v
    • 4
    • 20
  • s

    Slackbot

    03/19/2021, 12:53 AM
    This message was deleted.
    e
    s
    • 3
    • 2
  • t

    therealbluepandabear

    03/19/2021, 1:13 AM
    How would I clear the console in Kotlin?
    p
    e
    • 3
    • 3
  • s

    scott

    03/19/2021, 1:19 AM
    I am trying to use kotlinx serialization and I am working with the outlined basic example 3 in the kotlinx.serialization project. I am using Kotlin 1.4.31 and kotlinx.serialization 1.1.0. I am getting the attatched error even though I set up the test just like the example in the kotlinx.serialization code. Any thoughts on what I could be doing wrong? Or is this just a product of it still being in an experimental state.
    j
    d
    a
    • 4
    • 10
  • k

    KamilH

    03/19/2021, 10:19 AM
    I would like to use 
    Kodein-DB
     in the multiplatform library, however because of the fact that it depends on 
    serialization 1.1.0
     it forces me to upgrade kotlin version, because of this exception:
    Your current Kotlin version is 1.4.21, while kotlinx.serialization core runtime 1.1.0 requires at least Kotlin 1.4.30-M1.
    When I increase a version of Kotlin to 
    1.4.30
     problem disappears and it’s not a problem to do so on library side, but when I’m building a new version of my lib including 
    Kodein-DB
    and trying to run the app that includes my library compiler forces me to also upgrade Kotlin version on the app side (because it’s also using
    1.4.21
    ). Is there any possibility to overcome this problem? I wouldn’t like to force my clients to upgrade to Kotlin
    1.4.30
    u
    • 2
    • 1
  • t

    Tyluur

    03/19/2021, 2:57 PM
    It's for the runescape 2011 game, if anyone's interested =]
    ❤️ 1
    c
    j
    d
    • 4
    • 34
  • p

    PHondogo

    03/19/2021, 6:32 PM
    Hello! Does Kotlin supports top level delegates? If yes then how can i define operator fun getValue for that?
    c
    l
    • 3
    • 3
  • t

    therealbluepandabear

    03/20/2021, 3:18 AM
    Why can't we just do:
    class LootBox(item: Any) {
        private var loot = item
    }
    Instead of
    class LootBox<T>(item: T) {
        private var loot: T = item
    }
    m
    g
    • 3
    • 10
  • l

    Luiz Aguiar

    03/20/2021, 11:46 AM
    hey all! just as a (big) study exercise, I want to rewrite a cryptocurrency core in Kotlin, it's usually written in C++ or Rust. what should be the most efficient way to run it? Graalvm native? adoptjdk jvm (properly configured)? Kotlin Native? (only *unix support is enough) I don't expected to have the same "performance", but just want to discovery how to be the closest possible to the original project. Does anyone here has experience on cryptocurrencies core development?
    g
    r
    c
    • 4
    • 7
Powered by Linen
Title
l

Luiz Aguiar

03/20/2021, 11:46 AM
hey all! just as a (big) study exercise, I want to rewrite a cryptocurrency core in Kotlin, it's usually written in C++ or Rust. what should be the most efficient way to run it? Graalvm native? adoptjdk jvm (properly configured)? Kotlin Native? (only *unix support is enough) I don't expected to have the same "performance", but just want to discovery how to be the closest possible to the original project. Does anyone here has experience on cryptocurrencies core development?
g

Glen

03/20/2021, 1:29 PM
Hello @Luiz Aguiar. Please can you provide a link to the core library?
l

Luiz Aguiar

03/20/2021, 1:39 PM
The original in C++: https://github.com/nanocurrency/nano-node A rewrite in Rust: https://github.com/feeless/feeless
g

Glen

03/20/2021, 1:52 PM
I dont think I know enough to really give advice or opinion on what route you should take.
r

Robert Jaros

03/20/2021, 2:07 PM
https://medium.com/@vasilyf/lets-implement-a-cryptocurrency-in-kotlin-part-1-blockchain-8704069f8580
👍 1
c

CLOVIS

03/20/2021, 2:17 PM
About the different Kotlin versions: • Kotlin/JVM is optimized for throughput. It's a bit slow to startup, and it eats some RAM, but it's crazy fast when it's going. Best for servers/software that runs for a long time. • GraalVM Native is optimized to startup fast and have low latency. Best for command-line apps, stuff that needs to be started and stopped all the time. • Kotlin Native is optimized for low memory usage. Best for IoT, phones... I'm no where near an expert, it's just what I understand (so take with a grain of salt)
❤️ 2
g

Glen

03/20/2021, 2:38 PM
@Luiz Aguiar, I think you can look at the comparisons b/w the different options listed by @CLOVIS above and make a decision, based on what you consider as more important.
👍 1
l

Luiz Aguiar

03/20/2021, 3:03 PM
Thanks for the comments guys… I gonna do a bit more research on this topic, but I think I have some insights already. Any additional hint will be very appreciated.
View count: 2