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

    Mark Buikema

    06/23/2020, 1:59 PM
    Hi, I run into an issue... I have this class:
    data class Hotel(
      val id: String,
      val openStatus: OpenStatus //OpenStatus is an enum with values OPEN, PREORDER, CLOSED
      val favorite: Boolean
      val sortingValue: Int
    )
    Now I have a list of hotels. I want to sort the list in a way that it results in this:
    Open/preorder section (openStatus == OPEN || openStatus == PREORDER)
      Favorites
        Open
          Sorted by sortingvalue
        Preorder
          Sorted by sortingvalue
      Non-favorites
        Open
          Sorted by sortingvalue
        Preorder
          Sorted by sortingvalue
    Closed section (openStatus == CLOSED)
      Favorites
        Sorted by sortingvalue
      Non-favorites
        Sorted by sortingvalue
    What would be the best way to achieve this sorting behavior?
    z
    m
    • 3
    • 2
  • r

    Rob Murdock

    06/23/2020, 3:15 PM
    I’m probably alone in this, but… I keep running into situations where I want to take an anonymous object (with properties on it, natch) and then add new fields to it, creating a /new/ anonymous object with all the same fields but one or two more things on it.
    z
    m
    • 3
    • 17
  • t

    Toddobryan

    06/23/2020, 5:25 PM
    OK. After more testing, it turns out that trying to use
    kotlinc
    on code that references Scala 2.12.11's
    List
    (or any other class that references
    TraversableOnce
    ) causes the compiler to crash. A minimal example is:
    import scala.collection.JavaConverters.asScalaBuffer
    
    fun main() {
        val kotlinList: List<String> = listOf("abc", "def", "ghi")
        val scalaList = asScalaBuffer(kotlinList).toList
        println(scalaList)
    }
    This works fine with Scala 2.12.10, but won’t even compile with Scala 2.12.11. The difference seems to be https://github.com/scala/scala/blob/v2.12.10/src/library/scala/collection/TraversableOnce.scala#L102 vs https://github.com/scala/scala/blob/v2.12.11/src/library/scala/collection/TraversableOnce.scala#L117 where they introduced a
    reverser
    object that is confusing Kotlinc’s bytecode analysis.
    👍 3
    • 1
    • 1
  • v

    Vinicius Araujo

    06/23/2020, 6:57 PM
    Is it possible to have lazy extension properties with access to
    this
    ? This wont work:
    val Delegado.number: Int by lazy {
        println("Executed")
        this.id + 1
    }
    z
    • 2
    • 1
  • j

    Joakim Tengstrand

    06/23/2020, 7:56 PM
    I want to parse Kotlin code from Java (or actually Clojure, but Java is fine). I found this link explaining how to do it:
    <https://jitinsharma.in/posts/parsing-kotlin-using-code-kotlin/>
    Now I have converted that Kotlin code to Clojure, but when I try to access this field:
    public final val importList: org.jetbrains.kotlin.psi.KtImportList?
    Living in this class:
    org.jetbrains.kotlin.psi.KtFile
    In this library:
    org.jetbrains.kotlin/kotlin-compiler-embeddable "1.3.72"
    The problem is that this field is a val and that it's not annotated with @JvmField (that is my guess) and therefore I don't know how to access it. Can I use reflection or is there another way?
    k
    • 2
    • 1
  • t

    Twferrell

    06/24/2020, 12:43 AM
    Basic Kotlin question here. If I wanted to move the decimalPrecision into the when (for example when(decimalPrecision)), is there a way I can still compare the value against <= 0 ?
    🇳🇴 1
    r
    m
    • 3
    • 15
  • l

    lmj0011

    06/24/2020, 12:59 AM
    Could someone explain and/or provide a link that lays it out in layman terms what Kotlin DSL is and how its relates to
    build.gradle
    ? After reading https://www.raywenderlich.com/2780058-domain-specific-languages-in-kotlin-getting-started it's still not clicking.
    j
    m
    • 3
    • 2
  • k

    Ko Bokh

    06/24/2020, 11:01 AM
    Hi, can someone help me to enable xml reports for unit tests in a multiplatform project (gradle)? Currently, only a html report is generated. Many thanks.
    • 1
    • 1
  • x

    xii

    06/24/2020, 11:58 AM
    Hey! I have a question: What's an idiomatic way of doing this: I have a List<Foo> fooList , and Foo has properties .isA(), isB() which returns a boolean. I receive a list of properties 'state' with elements A, B, and I have to filter the list for those properties. I'm thinking of something like this:
    fooList.filter { if (state.contains('A') it.isA() else false || if (state.contains('B') it.isB() else false }
    but it looks ugly
    a
    j
    +3
    • 6
    • 11
  • r

    Robert Jaros

    06/24/2020, 1:22 PM
    Should
    internal
    field be visible from the test code? It works when I run compile and test tasks from Gradle, but when I work with code in IntelliJ it is marked as an error.
    b
    • 2
    • 7
  • k

    kushalp

    06/24/2020, 1:29 PM
    How are teams using Kotlin and Cucumber? It would be useful to understand how you've setup your
    build.gradle.kts
    files. Bonus points if it is configured using an entirely separate
    sourceSet
    m
    • 2
    • 1
  • p

    Philipp Mayer

    06/24/2020, 1:37 PM
    Hello guys, I basically want to do the following:
    class Dto(val name: String, val age: Int, val somethingElse: String) {
        var signedKey = ""
    
        fun encrypt(shaSign: String): String {
            /*do something with all constructor fields*/
            return "encryptedString"
        }
    }
    the function
    encrypt(shaSign: String)
    returns an encrypted string by hashing the fields
    name
    ,
    age
    and
    somethingElse
    . I basically just want to set the field
    signedKey
    with the output of that operation.
    val dto = Dto("John", 36, "something else")
    dto.signedKey = dto.encrypt("someShaKey")
    Ofc I could do it like that, but that is really not a good way. I thought a bout a distinct setter which takes a parameter (some sign), executes
    encrypt
    and places the returned value as
    signedKey
    . How could I achieve that? Thanks ahead!
    a
    a
    m
    • 4
    • 11
  • g

    Gopal S Akshintala

    06/25/2020, 4:02 AM
    Is there a way to convert Kotlin to Readable Java?
    d
    i
    +3
    • 6
    • 6
  • u

    user

    06/25/2020, 9:23 AM
    message has been deleted
    d
    v
    +2
    • 4
    • 16
  • i

    Ifvwm

    06/25/2020, 9:53 AM
    is that possible to make Int and String to inherit an interface?
    🇳🇴 1
    🙅‍♀️ 4
    d
    • 2
    • 1
  • b

    bod

    06/25/2020, 10:00 AM
    Hello, World! Isn't there a shorter way to do this (with
    by
    )?
    var parameter: Parameter
            set(value) {
                delegate.parameter = value
            }
            get() = delegate.parameter
    m
    j
    r
    • 4
    • 10
  • i

    iex

    06/25/2020, 11:02 AM
    Hi! I moved my domain logic classes to a new module, and getting this error:
    Smart cast to 'UserInput.Some' is impossible, because 'alert.earliestSymptomTime' is a public API property declared in different module 
    code:
    when (alert.earliestSymptomTime) {
        is UserInput.Some -> alert.earliestSymptomTime.value.value
        is UserInput.None -> null
    }
    Why does it happen? Seems weird. And is there a way to fix it without having to cast? I didn't expect that modularizing my app would lead to a decline in code quality 😕
    j
    k
    r
    • 4
    • 8
  • m

    manueldidonna

    06/25/2020, 2:36 PM
    Does a function reference allocate a new object?
    data class Item(val id: Int)
    fun randomItem(block: (Int) -> Item) {}
    
    // this
    List(100) { randomItem(::Item) }
    
    // vs
    val constructor = ::Item
    List(100) { randomItem(constructor) }
    z
    • 2
    • 4
  • j

    Joel

    06/25/2020, 10:47 PM
    assertEquals(
                BigDecimal("0.08333333333333333"),
                (1.toBigDecimal() / 12.toBigDecimal())
            )
    
    expected: <0.08333333333333333> but was: <0>
    The bottom evaluates to
    0
    which is clearly incorrect. What is the rule here and how can I avoid this pitfall?
    r
    • 2
    • 6
  • s

    Slackbot

    06/26/2020, 8:36 AM
    This message was deleted.
    a
    a
    • 3
    • 3
  • s

    sikri

    06/26/2020, 8:44 AM
    Why does
    coerceAtLeast
    has more priority then
    -
    ?
    -2.coerceAtLeast(0) == -2
    m
    b
    • 3
    • 15
  • j

    Joakim Tengstrand

    06/26/2020, 12:14 PM
    I want to call Kotlin functions from Java, but when I disassamble the compiled Kotlin code, I can see that the types are e.g. kotlin.String instead of java.lang.String. Is there a way to compile the Kotlin code to Java types directly, or do we need to call the Kotlin code with e.g. kotlin.String, and if so, how do we convert from Java types to Kotlin types?
    d
    • 2
    • 8
  • t

    torres

    06/26/2020, 1:13 PM
    Why does line 6 still prints "A" here, see https://stackoverflow.com/questions/62595494/linkedlist-remove-element-puzzle
    fun main(args: Array<String>) {
            var tree = Node("A", null, null)
            val q: Queue<Node> = LinkedList()
            q.add(tree)
            tree = q.remove() // line 5, remove element in q and assign to tree so tree so should size 0
            println(tree.data) // line 6, why does this still print "A" though?
    }
    // given
    class Node {
        var data: String
        var left: Node? = null
        var right: Node? = null
    
        constructor(data: String) {
            this.data = data
        }
    
        constructor(data: String, left: Node?, right: Node?) {
            this.data = data
            this.left = left
            this.right = right
        }
    }
    d
    m
    • 3
    • 16
  • r

    rrva

    06/26/2020, 2:04 PM
    is there some good reading material on how people stylistically handle the fact that you can have top-level functions without classes in Kotlin? Do you ever create stateless classes or is it more common to just declare stuff with functions and import the function?
    a
    • 2
    • 2
  • e

    evanchooly

    06/26/2020, 4:11 PM
    if parsing/generating kotlin is your thing, there’s also my kibble project: https://github.com/evanchooly/kibble
    j
    • 2
    • 5
  • z

    Zach Klippenstein (he/him) [MOD]

    06/26/2020, 7:23 PM
    Are inline classes okay to use for internal-only code in libraries, i.e. if they’re not exposed as part of the public API?
    👀 2
    j
    • 2
    • 1
  • a

    Antonios Barotsis

    06/26/2020, 8:32 PM
    How does reading files with kotlin work? I want to read a json file and parse it, im on a javascript with gradle project
    n
    l
    • 3
    • 4
  • n

    nkiesel

    06/27/2020, 12:14 AM
    I just got a frontend compiler bug in Intellj (when trying to run my code). This used to work w/o problems until a few moments ago. "Invalidate cache and restart" did not help. IntellJ uses 720 of 1950MB right now.
    Error:Kotlin: [Internal Error] java.rmi.ServerError: Error occurred in server thread; nested exception is: 
    	java.lang.OutOfMemoryError: Java heap space
    	at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:386)
    	at sun.rmi.transport.Transport$1.run(Transport.java:200)
    	at sun.rmi.transport.Transport$1.run(Transport.java:197)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    	at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
    	at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
    	at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    	at java.lang.Thread.run(Thread.java:748)
    	at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:303)
    	at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:279)
    ...
    Caused by: java.lang.OutOfMemoryError: Java heap space
    	at org.jetbrains.kotlin.incremental.storage.ProtoMapValueExternalizer.read(externalizers.kt:63)
    	at org.jetbrains.kotlin.incremental.storage.ProtoMapValueExternalizer.read(externalizers.kt:48)
    	at com.intellij.util.io.PersistentHashMap.doGet(PersistentHashMap.java:616)
    	at com.intellij.util.io.PersistentHashMap.get(PersistentHashMap.java:560)
    	at org.jetbrains.kotlin.incremental.storage.CachingLazyStorage.get(CachingLazyStorage.kt:64)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCache$ProtoMap.get(IncrementalJvmCache.kt:307)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCache.getModuleMappingData(IncrementalJvmCache.kt:267)
    d
    j
    i
    • 4
    • 5
  • p

    Paul Woitaschek

    06/27/2020, 7:58 AM
    Isn't map.getOrPutBroken? Maps support null values, but getOrPut calls the lambda if there is a null value for a key
    r
    • 2
    • 1
  • a

    Antonios Barotsis

    06/27/2020, 10:40 AM
    Is it possible to target both JVM and JS?
    i
    a
    n
    • 4
    • 5
Powered by Linen
Title
a

Antonios Barotsis

06/27/2020, 10:40 AM
Is it possible to target both JVM and JS?
i

Iaroslav Postovalov

06/27/2020, 12:42 PM
Yes, https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html
👍 3
a

Antonios Barotsis

06/27/2020, 12:42 PM
thanks i just found out about this!
a

andylamax

06/27/2020, 12:53 PM
And It is great. I use kotlin mpp targeting android,jvm and js in production. And it works flawlessly
a

Antonios Barotsis

06/27/2020, 1:06 PM
This seems very useful yeah
n

Nikky

06/27/2020, 11:00 PM
it is also possible to then bundle the js and resources into a shadowJar, very useful for ktor serving static content
View count: 2