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

    Reprator

    03/31/2020, 11:49 AM
    Hi Mates, i need a help in writing unit test cases for a top level function, if possible can you guys help me to get through this, Stackoverflow question , thanks in advance, apology if i am in wrong channel
    :google: 2
    d
    • 2
    • 2
  • h

    Hamza

    03/31/2020, 12:07 PM
    <template name="sout" value="println($END$)" description="Prints a string to System.out" toReformat="true" toShortenFQNames="false"> Is it possible to create a live kotlin template like
    {statement}.{{templateName}}
    ? Similar to how doing something like
    val x = "hi"
    x.sout <Tab> // -> println(x)
    ATM, I just duplicated the sout template and added my own, but it doens't work where I call it on another variable. Is that even possible? So I can do something like
    x.{{templateName}}<Tab> // -> Something.doSomething(x)
    m
    • 2
    • 3
  • e

    Edoardo Luppi

    03/31/2020, 12:58 PM
    Hi guys. Are these two operations equal in Kotlin?
    """[ \t\f\v]+""".toRegex()
    "[ \\t\\f\\v]+".toRegex()
    h
    • 2
    • 4
  • s

    sbyrne

    03/31/2020, 2:02 PM
    I have a
    private val done:MutableSet<T> = mutableSetOf()
    in a class. Method
    a
    starts a thread which calls method
    b
    , which has
    synchronized(done)
    . I intermittently get an NPE on
    synchronize(done)
    . I moved the
    private val done
    declaration from between
    a
    and
    b
    to above
    a
    and that seems to have fixed it. Am I crazy?
    z
    • 2
    • 5
  • i

    iex

    03/31/2020, 2:58 PM
    Hi. How to implement properly
    equals
    and
    hashcode
    for a data class that contains a
    ByteArray
    ?
    s
    a
    d
    • 4
    • 9
  • s

    Sam Garfinkel

    03/31/2020, 5:55 PM
    Anyone know why type checking hates the
    val foo: String? by defaultProperty { null }
    ? It only goes away by explicitly defining the type of
    defaultProperty<String?>
    Untitled
    l
    d
    • 3
    • 14
  • s

    Slackbot

    04/01/2020, 5:48 AM
    This message was deleted.
    d
    i
    • 3
    • 3
  • c

    Chills

    04/01/2020, 9:11 AM
    why secondary constructor needs to point to base constructor?
    d
    m
    • 3
    • 25
  • e

    Edoardo Luppi

    04/01/2020, 9:52 AM
    Morning 😄 I currently have a sequential operation which uses a
    Sequence<T>
    myProviders
      .asSequence()
      .sortedBy(configService::getProviderOrder)
      .flatMap { it.getCommitTypes(context.type) }
      .map { CommitTypePsiElement(project, it) }
      .mapIndexed(::CommitTypeLookupElement)
      .distinctBy(CommitTypeLookupElement::getLookupString)
      .forEach(rs::addElement)
    Each
    provider
    call (
    it.getCommitTypes(context.type)
    ) returns a
    Collection<T>
    and cannot be converted to Flows. I would like to call every provider asynchronously and then
    flatMap
    the results, and
    collect
    . How would you approach this in the code above? This part
    .map { CommitTypePsiElement(project, it) }
    .mapIndexed(::CommitTypeLookupElement)
    .distinctBy(CommitTypeLookupElement::getLookupString)
    .forEach(rs::addElement)
    can remain sequential / blocking.
    m
    • 2
    • 42
  • u

    user

    04/01/2020, 10:43 AM
    message has been deleted
    👍 6
    m
    c
    • 2
    • 2
  • u

    ulrikguenther

    04/01/2020, 2:38 PM
    hi everyone! i have a question regarding the removal of type parameters from objects in 1.4: what is the reasoning there, and what is the suggested replacement?
    a
    l
    • 3
    • 7
  • t

    Twferrell

    04/01/2020, 3:33 PM
    Hi all, I have a strange one here... So I'm trying to build a DSL in Kotlin and came across a scenario where I want to combine a set of symbols that are currently dispersed in various different packages behind one single, new package namespace. That way the folks using my DSL to author their own scripts don't have to import symbols from so many different packages. I came up with one idea of using type aliases, but I have so many symbols, I don't want to duplicate these and hard code each alias for all the various entities (not very DRY and difficult to maintain). Example (let's say Alabama is an "object" extending from State) // Aliasing example: typealias Alabama = com.some.other.package.states.Alabama typealias Alaska = com.some.other.package.states.Alaska typealias Electronics = com.some.yet.another.package.products.Electronics ... // For DSL magic: infix fun State.eq(other: State) = this == other // Then within the DSL I have: package com.dsls import com.combined.symbols.* rules { when (state eq ALABAMA) { true -> doSomething... false -> doSomethingElse... } }
    s
    r
    +2
    • 5
    • 15
  • g

    Gunslingor

    04/01/2020, 4:17 PM
    Has anyone been reading about Kotlin 1.4? I'm specifically wondering about the KotlinJS changes coming. To be really specific: I have multiple multiplatform projects going. One is setup with frontend/common/backend main/test. Another project is (hopefully going to be) setup with ios/android/web/common main/test... but now I have this dilemma of what to do with the web app, since it would need frontend/common/backend main/test but that's getting confusing, complicated and no idea the right way to set it up; So in reading online it sounds like frontend and backend are effectively being merged in this scenario. Is this correct and is this intended to fix the situation in which I describe?
    d
    • 2
    • 3
  • i

    iex

    04/01/2020, 8:08 PM
    Hi folks,
    fold
    is less performant than a loop, right? Specifically:
    bytes.fold("") { acc, byte -> acc + String.format("%02X", byte) }
    vs
    var ret: String = ""
    for (b in bytes) {
        ret += String.format("%02X", b)
    }
    return ret
    j
    • 2
    • 6
  • c

    Chills

    04/02/2020, 5:47 AM
    Is open source projects are considered as work experience, were you are major contributor?
    a
    • 2
    • 4
  • s

    steenooo

    04/02/2020, 9:55 AM
    What stdlib should I use for using EAP 1.4? It can't find this
    • 1
    • 1
  • z

    zalewski.se

    04/02/2020, 12:31 PM
    Can someone explain me why the result of this code is false? Why
    log(243.0, 3.0)
    returns 4.999999999999999 😮
    Untitled
    d
    m
    +2
    • 5
    • 12
  • h

    Holger Steinhauer [Mod]

    04/02/2020, 3:32 PM
    Hey folks. Join us tonight at 7pm CEST on YouTube (https://www.youtube.com/channel/UCG2hmX2Jda7158gMCBUOyTQ) for our Virtual Kotlin Meetup! Two talks, in English of course!
    🤘 1
    n
    b
    • 3
    • 10
  • t

    Twferrell

    04/02/2020, 8:04 PM
    Hi all, so real quick...Anyone know the magic sauce of how to prevent duplicates (see the calc block in the screenshot below)? As you can see, I am able to prevent calc from being called within calc (by use of the DslMarker annotation), but how do I prevent duplicate siblings?
    d
    • 2
    • 5
  • g

    Gilberto Diaz

    04/03/2020, 1:39 AM
    I ran into this paper today and thought it would be a good idea to leave it here. @hhariri wondering if this will play well together with kotlin.
    Disruptor-1.0.pdf
    h
    t
    • 3
    • 3
  • c

    Chung

    04/03/2020, 2:47 AM
    I have a variable
    edge = Edge1(__typename=CmsCarouselImageEdge, .....)
    and I would like to define my own data class
    data class MyClass
    rather than return this variable as
    Edge1
    . how do I do it in Kotlin?
    val my_data: MyClass = edge as MyClass
    m
    • 2
    • 4
  • v

    Vitali Plagov

    04/03/2020, 8:41 AM
    Hi. I have two data classes:
    data class ScopeGroup(
          val id: UUID,
          val scopeOptions: List<ScopeOption>
    )
    and
    data class ScopeOption(
          val id: UUID,
          val status: String
    )
    So, the service returns a list of
    ScopeGroup
    with several
    ScopeOption
    inside. I want to filter this list so that
    ScopeGroup
    has a list of only those
    ScopeOption
    that has a certain status. I did this:
    list.flatMap { group -> group.scopeOptions.filter { option -> option.status == "ACTIVE" } }
    But it returns
    List<ScopeOption>
    . Is it possible to return
    List<ScopeGroup>
    instead?
    m
    j
    n
    • 4
    • 20
  • c

    CFrei

    04/03/2020, 8:47 AM
    class A
    class B
    open class C
    open class D
    val a: A = A()
    val c: C = C()
    
    a is B // <-- as expected: error
    c is D // <-- not expected: no error
    As expected I get an "Incompatible types B and A"-error at compile time for the line
    a is B
    . But not for the next line
    c is D
    . Is there any chance that
    c
    could be of type
    D
    or is this a missing feature in the compiler? Does anyone have an example?
    d
    m
    • 3
    • 7
  • e

    Erik

    04/03/2020, 10:21 AM
    Because I extracted
    val isString
    ,
    x
    inside the if-statement cannot be smart cast to `String`:
    val x: Any = "foo"
    val isString = x is String
    if (isString) {
        x + "bar" // Error, cannot smart cast x to String
    }
    val y = isString
    Which of the following two options is preferred and why, or is there another idiomatic way to do this? 🅰️:
    val x: Any = "foo"
    val isString = x is String
    if (isString) {
        x as String + "bar" // Dumb cast x to String
    }
    val y = isString
    🅱️:
    val x: Any = "foo"
    if (x is String) {
        x + "bar"
    }
    val y = x is String // Repeat the type check
    You can vote 🅰️, 🅱️, or reply in the thread for reasons why (not) to go for 🅰️ or 🅱️, or another option. Thanks! 🙂
    w
    m
    • 3
    • 7
  • v

    vinay

    04/03/2020, 10:55 AM
    Is there a way to suppress specific kotlin compiler warnings?
    w: ATTENTION!
    This build uses unsafe internal compiler arguments:
    
    -XXLanguage:+InlineClasses
    i
    • 2
    • 2
  • g

    Grantas33

    04/03/2020, 5:37 PM
    Hello. My root gradle project consists of two gradle subprojects- the backend (jvm) and the frontend (js gradle plugin). I want to extract the duplicate code for the data classes from both projects into some sort of a common module, so that I can share the data classes. Is there an easy way to share the code without creating a multiplatform project?
    d
    • 2
    • 1
  • b

    bmarinovic

    04/03/2020, 7:12 PM
    hi, does Kotlinx.serialization provides out of the box serialization for some Date class? I’ve tried Joda and java.time.LocalDate and it complains there’s no serializer for that types
    g
    • 2
    • 2
  • g

    gammax

    04/04/2020, 4:09 PM
    Hi all, I’m looking for a compiler flag to selectively raise some Kotlin compiler warnings to errors. I know there is a
    -Werror
    flag that will turn all warnings to errors. I’d love to raise only some of them. Do you have any ideas on where to investigate?
    b
    • 2
    • 3
  • d

    Deanfarwell

    04/04/2020, 5:37 PM
    I am trying to get Kotlin Worksheets within IntelliJ to recognize classes available within the project. I can get it to import my classes but it will not pull in classes form libraries included via Gradle Dependencies. Specifically, I have the following in my build.gradle
    implementation "io.arrow-kt:arrow-core:$arrow_version"
    m
    a
    • 3
    • 4
  • g

    Gunslingor

    04/04/2020, 8:01 PM
    Here's a joke: How many engineers does it take to make ktor/exposed/klaxon work together? None, it seems to be impossible. Strange thing is that I had this working prefectly before I converted Reports from Table to IntIdTable and Report to an IntEntity; I also added releationships/references and primary keys and default values since it last worked. Does anyone see what I am doing wrong here?
    fun Any.jsonToString(prettyPrint: Boolean): String{
            var thisJsonString = Klaxon().toJsonString(this)
            var result = thisJsonString
            if(prettyPrint) {
                if(thisJsonString.startsWith("[")){
                    result = Klaxon().parseJsonArray(thisJsonString.reader()).toJsonString(true)
                } else {
                    result = Klaxon().parseJsonObject(thisJsonString.reader()).toJsonString(true)
                }
            }
            return result
        }
    routing {
        route("report") {
            route("get") {
                get("all") {
                    call.respondText {
                        dbConnect()
                        val reports = transaction { Report.all().toList() }
                        Klaxon().jsonToString(reports)
                    }
                }
    • 1
    • 1
Powered by Linen
Title
g

Gunslingor

04/04/2020, 8:01 PM
Here's a joke: How many engineers does it take to make ktor/exposed/klaxon work together? None, it seems to be impossible. Strange thing is that I had this working prefectly before I converted Reports from Table to IntIdTable and Report to an IntEntity; I also added releationships/references and primary keys and default values since it last worked. Does anyone see what I am doing wrong here?
fun Any.jsonToString(prettyPrint: Boolean): String{
        var thisJsonString = Klaxon().toJsonString(this)
        var result = thisJsonString
        if(prettyPrint) {
            if(thisJsonString.startsWith("[")){
                result = Klaxon().parseJsonArray(thisJsonString.reader()).toJsonString(true)
            } else {
                result = Klaxon().parseJsonObject(thisJsonString.reader()).toJsonString(true)
            }
        }
        return result
    }
routing {
    route("report") {
        route("get") {
            get("all") {
                call.respondText {
                    dbConnect()
                    val reports = transaction { Report.all().toList() }
                    Klaxon().jsonToString(reports)
                }
            }
I think I figured it out... it was working earlier because I was mapping the Table object to a class without inherentance and mostly just string objects before sending to klaxon.
View count: 3