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

    iex

    01/21/2020, 3:39 PM
    Not sure if this is the right place to ask, as it involves a third party... But it's also related with the lang. I have a problem with Gson lib, that the api can send empty string as a date. I declared this adapter to tell Gson how to deserialize a date:
    registerTypeAdapter(Date::class.java, DateDeserializer())
    So when the object has a non optional
    Date
    , it's clear that I should throw an exception if it gets an empty string. But when
    Date
    is optional, I'd like to map the empty string to
    null
    , i.e. the date will just be assigned
    null
    . Not sure how to do that. It relates with lang, in that the deserializer is defined like this: `JsonDeserializer<Date>`but I need it to work with
    Date?
    basically. I can of course create a getter in my object that deserializes the date if present, but I'd like to do this directly with the parser, not "outside".
    r
    d
    • 3
    • 10
  • s

    Sam Schilling

    01/21/2020, 4:58 PM
    Is using an upper-bound generic any different from just using that super type directly? E.g.,
    open class Animal { ... }
    
    // Using upper bound generic
    fun <T: Animal> print(animal: T) { ... }
    
    // Using type directly
    fun print(animal: Animal) { ... }
    It seems in both cases any subclasses of
    Animal
    will work with the function call. In which case the second option seems more readable and condensed if they function identically.
    s
    c
    +2
    • 5
    • 16
  • s

    Sandy

    01/21/2020, 5:32 PM
    I would like to like to write a regex to replace unicode characters in string. Was trying something like str.replace("\\\\u\\d{4}", "")
    s
    • 2
    • 2
  • w

    Wesley Acheson

    01/21/2020, 5:44 PM
    Okay I know you can have sealed classes for a when check to verify that you are covering all branches. is the reverse possible say given a string input I output all sealed classes under a hirachy? I'm guessing no the type checker can't verify
    g
    h
    s
    • 4
    • 5
  • l

    LeoColman

    01/21/2020, 7:41 PM
    Hey guys! Is Kotlin JS deprecated? Or are people using it actively?
    s
    c
    +2
    • 5
    • 16
  • l

    luke

    01/22/2020, 4:07 AM
    Anyone any good with Regex? Struggling with this.
    1914   1    5.9     0.9    ---     48.3    ---
    What I have so far:
    ([\d]+)\.*([\s]+)
    I just want to extract all the non-whitespace values into an Array.
    r
    • 2
    • 7
  • a

    AnnoymousGiraf

    01/22/2020, 4:15 AM
    Hi, as any one encounter this type of class def and can explain the pattern
    Class A cosntructor(...) : (String) -> B {
    
    }
    r
    e
    • 3
    • 6
  • u

    user

    01/22/2020, 12:33 PM
    Kotlin Census 2019: Call for Respondents You can read this blog post in other languages: The new edition of Kotlin Census is here! By the end of 2019, more than 4 million people had used Kotlin. This is a great number of people, and of course, … Continue reading →
    k
    t
    • 2
    • 3
  • i

    iex

    01/22/2020, 3:02 PM
    Hi folks! Is there a functional way to write this?
    for (handler in handlers) {
        if (handler.handle(uri)) break
    }
    s
    d
    +3
    • 6
    • 15
  • r

    René

    01/22/2020, 7:04 PM
    Has someone an working example of a mocked class where you want to verify that one given method was called once? I tried
    verify(sut).someMethod("example")
    , but that throws always 3 invocations (two other where on other methods). I have right now no idea how to fix that test
    b
    m
    • 3
    • 7
  • d

    David Glasser

    01/22/2020, 7:35 PM
    I'm trying to understand why it's legal to call a function whose generic type is reified from another function whose generic type is not reified. Something like
    inline fun <T : Any> foo(X<T>): List<T> {
      return objectMapper.readValue(xxx)
    }
    inline fun <reified T> ObjectMapper.readValue(content: String): T = ... # from jackson kotlin
    How does the compiler create the reification of the T in the nested function if it's not reified in the outer function?
    c
    • 2
    • 3
  • e

    Ellen Spertus

    01/22/2020, 7:59 PM
    Is there a more elegant way to write this (besides writing a helper method):
    var method: String? = null
    try {
        method = jsonResponse.getString("method")
    } catch (exception: JSONException) {
        Log.i(TAG, "No method provide by server.")
    }
    d
    m
    • 3
    • 4
  • m

    Michael Friend

    01/22/2020, 10:20 PM
    When making a safe cast on an object that might be null, is there a difference between
    val casted = nullable as? String
    and
    val casted = nullable as String?
    ? They both smart cast to
    String?
    but do they both give null if
    nullable
    is null and
    nullable
    casted to a string (assuming the cast is possible)? I know using
    as?
    returns null if the cast fails and i assume option 2 would throw an exception, is that the only difference?
    r
    • 2
    • 2
  • t

    trathschlag

    01/23/2020, 8:42 AM
    Is there an ergonomic way to make constructors file-visible only?
    s
    • 2
    • 2
  • r

    ribesg

    01/23/2020, 10:29 AM
    var result: Result<T>? = null
    // ...
    return result!!.getOrThrow() // Expression of type kotlin.Result cannot be used as a left operand of '!!'
    What is that supposed to mean? Why do I have to write
    (result as Result<T>).getOrThrow()
    for it to compile?
    d
    • 2
    • 1
  • m

    Marcin Wiśniewski

    01/23/2020, 10:30 AM
    Hi, during project compilation (maven 3.6.3, kotlin 1.3.61) I received following error:
    [INFO] Possible cache corruption. Rebuilding. <http://com.intellij.util.io|com.intellij.util.io>.PersistentEnumeratorBase$CorruptedException: PersistentEnumerator storage corrupted /builds/swb/api/api/target/kotlin-ic/compile/caches-jvm/inputs/source-snapshot.tab
    <http://com.intellij.util.io|com.intellij.util.io>.PersistentEnumeratorBase$CorruptedException: PersistentEnumerator storage corrupted /builds/swb/api/api/target/kotlin-ic/compile/caches-jvm/inputs/source-snapshot.tab
        at <http://com.intellij.util.io|com.intellij.util.io>.PersistentEnumeratorBase.<init>(PersistentEnumeratorBase.java:221)
        at <http://com.intellij.util.io|com.intellij.util.io>.PersistentBTreeEnumerator.<init>(PersistentBTreeEnumerator.java:73)
        at <http://com.intellij.util.io|com.intellij.util.io>.PersistentEnumeratorDelegate.<init>(PersistentEnumeratorDelegate.java:47)
        at <http://com.intellij.util.io|com.intellij.util.io>.PersistentHashMap.<init>(PersistentHashMap.java:163)
        at <http://com.intellij.util.io|com.intellij.util.io>.PersistentHashMap.<init>(PersistentHashMap.java:152)
        at <http://com.intellij.util.io|com.intellij.util.io>.PersistentHashMap.<init>(PersistentHashMap.java:143)
        at <http://com.intellij.util.io|com.intellij.util.io>.PersistentHashMap.<init>(PersistentHashMap.java:135)
        at <http://com.intellij.util.io|com.intellij.util.io>.PersistentHashMap.<init>(PersistentHashMap.java:128)
    Problem occurs only on Gitlab-CI pipeline. Compilation on local machine works well. Can anybody help me to fix it?
    👀 1
    a
    • 2
    • 1
  • r

    ribesg

    01/23/2020, 11:13 AM
    Found a bug, curly braces are required here. Autofix removes the label
    i
    • 2
    • 2
  • m

    Michael de Kaste

    01/23/2020, 1:56 PM
    play and try kotlinlang.org is down?
    p
    • 2
    • 1
  • i

    Ianmedeiros

    01/23/2020, 5:46 PM
    How do you guys handle object serialization in the context of Sealed classes? This is a behaviour that we get for “free” with enums.
    sealed.txt
    k
    t
    • 3
    • 5
  • t

    tipsy

    01/23/2020, 8:45 PM
    i have a colleague who makes typealias for everything, like:
    typealias Address = String
    typealias Age = Int
    when i see these typealiases used in signatures, i always assumed they're classes is there a guideline on this? i personally find it very confusing, but it might just be because it's unfamiliar
    🤔 4
    n
    d
    +5
    • 8
    • 21
  • v

    voben

    01/24/2020, 8:44 AM
    Can I catch 2 exceptions at once in kotlin like we do in java?
    // Java code
    try {
        return doDangerousThing();
    } catch (ExceptionA | ExceptionB e) {
        e.printStackTrace();
    }
    t
    e
    +2
    • 5
    • 5
  • g

    GarouDan

    01/24/2020, 9:57 AM
    Hi, In order to configure my build I need to expose some private methods from a 3rd party plugin. Can I do that using Kotlin extensions? The plugin in question is the
    xcode-compat
    , and the method that I’d like to expose is
    setupTask
    (which is available here: https://github.com/Kotlin/xcode-compat/blob/6633fe0696c38c9eee2f789164b8b945910fdc13/xcode-compat/src/main/kotlin/org/jetbrains/kotlin/xcodecompat/XcodeCompatPlugin.kt#L27) Please also note that this method will depend on other private ones. I tested copying and pasting the plugin locally and then applying it, it works after that, but I don’t know if I can do that without forking the plugin. Can we?
    g
    • 2
    • 6
  • r

    redenergy

    01/24/2020, 11:44 AM
    How to debug and fix issues with Database class initialization like this? I have included exposed-jdbc dependency but the exception is still here. Quick googling yielded only one issue on github without a proper solution. I suspect it has something to do with different classloaders but I am not sure where to start
    java.lang.NoClassDefFoundError: Could not initialize class org.jetbrains.exposed.sql.Database
    	at gloomyfolken.bundle.common.mysql.MysqlContext.<init>(MysqlContext.kt:33)
    	at gloomyfolken.bundle.common.mysql.MysqlWorkerThread.openConnection(MysqlWorkerThread.kt:98)
    	at gloomyfolken.bundle.common.mysql.MysqlWorkerThread.run(MysqlWorkerThread.kt:109)
    Caused by: java.lang.IllegalStateException: Can't load implementation for DatabaseConnectionAutoRegistration
    	at org.jetbrains.exposed.sql.Database.<clinit>(Database.kt:64)
    	... 3 more
    • 1
    • 1
  • y

    ylemoigne

    01/24/2020, 12:25 PM
    Edited question : Is there any syntax that allow for a premature return in when case block ? If a such thing is possible, what it look like ? (Original question : Hello, I have difficulties to find the right syntax (jump label ?) to return from a
    when
    clause)
    Eg :
    fun main() {
        val myShortCutCondition = true
        val s = when(2){
            1 -> {
                if(myShortCutCondition){
                    // return "shortcut" // for `s` value
                }
                
                // longCode
                
                "1"
            }
            2 -> "2"
            else -> ""
        }
    }
    m
    e
    +3
    • 6
    • 18
  • n

    natpryce

    01/24/2020, 2:56 PM
    Jackson can parse YAML to a tree of JsonNode objects.
    😮 1
    m
    • 2
    • 7
  • g

    Georgi Naumov

    01/25/2020, 3:22 PM
    Would you suggest how to make that code better: https://gist.github.com/gonaumov/567f756fba95ad6b30bbab575b2f2fba
    s
    n
    • 3
    • 2
  • n

    Nick Halase

    01/25/2020, 8:32 PM
    Does Jetbrains have a place for us to discuss the Space EAP? I'm in the middle of setting up Space for my workplace and I have general questions about best-practice that I can't find answers to in the documentation (yes I realize this is EAP access).
    s
    • 2
    • 1
  • p

    poohbar

    01/26/2020, 2:27 AM
    Is there any built-in for
    String
    to ensure that a string ends with a certain character? Also called "append if missing" in some libraries. e.g.
    foo("word", ".")
    ->
    word.
    foo("word.", ".")
    ->
    word.
    n
    • 2
    • 1
  • o

    otakusenpai

    01/26/2020, 8:32 AM
    Hi, Just created a mpp prohect using gradle in IDEA. How do i add another module named "common" module?
    r
    • 2
    • 11
  • o

    otakusenpai

    01/26/2020, 1:57 PM
    I was reading someone's code for some thing and found this strange class definition
    class Usage(from: List<UsageArgument> = listOf(), val runsAt: List<RunAt> = listOf()) : List<UsageArgument> by from {
        override fun toString(): String {
            val result = joinToString(" ") { it.format() }
    
            return if (result.isBlank()) "none" else result
        }
    }
    can anyone explain this to me? especially the parameters of the class def and the ending "by from". what does it mean? the use case is like a list or something i suppose?
    c
    f
    r
    • 4
    • 5
Powered by Linen
Title
o

otakusenpai

01/26/2020, 1:57 PM
I was reading someone's code for some thing and found this strange class definition
class Usage(from: List<UsageArgument> = listOf(), val runsAt: List<RunAt> = listOf()) : List<UsageArgument> by from {
    override fun toString(): String {
        val result = joinToString(" ") { it.format() }

        return if (result.isBlank()) "none" else result
    }
}
can anyone explain this to me? especially the parameters of the class def and the ending "by from". what does it mean? the use case is like a list or something i suppose?
c

Chills

01/26/2020, 2:00 PM
strange?
f

Foso

01/26/2020, 2:01 PM
"by" is a keyword for Delegation https://kotlinlang.org/docs/reference/delegation.html
c

Chills

01/26/2020, 2:11 PM
delegation is a hard topic
to wrap your head around it , look at delegation pattern before hand.
r

Ray Eldath

01/26/2020, 6:49 PM
off-topic: i remembered KotlinConf 2018 Closing Panel someone pointed delegation as their most hateful feature. and in ktconf 2019 Andrej says delegation is what he want to redesign most, IIRC.
View count: 1