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

    Tim Malseed

    01/17/2020, 1:08 AM
    Is it possible to suppress the
    NAME_SHADOWING
    warning in Kotlin, globally? If not, where would I file a request for this feature?
    r
    a
    • 3
    • 5
  • r

    rcd27

    01/17/2020, 8:15 AM
    Just a hint for every
    Kotlin
    programmer: you are pretty able to write
    Scala
    as well 🙂 Decided to shift to FP, and realized that
    JetBrains
    prepared me for that stuff somehow ❤️
    t
    n
    • 3
    • 4
  • j

    Joost de Vries

    01/17/2020, 9:41 AM
    With regards to type arguments for a function, is there a way not to have to specify all three when calling this function? https://pl.kotl.in/kMoCgjgsg That would be a very handy utility function to have for our codebase but having to specify superfluous type arguments undoes the value.
    s
    r
    • 3
    • 18
  • j

    Jérôme Gully

    01/17/2020, 10:29 AM
    Hi, I try to make a Builder in Kotlin, all was fine with this sample code I inspirate from, but my goal is to consume it in Java (Kotlin default parameters = Overload methods), so the Builder pattern in Kotlin is not usefull to use in Java with this sample code. what alternatives I have ?
    Builder
    f
    m
    s
    • 4
    • 7
  • i

    iex

    01/17/2020, 10:37 AM
    Hi folks, I'm trying to create a data type aking to
    Result<T>
    but which 1) Can return an arbitrary type as error and 2) Doesn't have a success payload. Here's the solution I came up with. I wonder if it can be expressed more elegantly?
    sealed class EmptyResult<E> {
        class Success<E> : EmptyResult<E>()
        data class Failure<E>(val error: E): EmptyResult<E>()
    }
    
    fun foo(): EmptyResult<String> = EmptyResult.Success()
    d
    h
    s
    • 4
    • 7
  • a

    armaxis

    01/17/2020, 3:33 PM
    Hey folks, I might be missing something, but why IDE is not complaining about unsafe cast if following snippet?
    val nullableList: List<String>? = listOf()
    val nonNullableList: List<String> = nullableList as List<String>
    p
    a
    +2
    • 5
    • 26
  • i

    iex

    01/17/2020, 4:22 PM
    I can't have private interface vals / functions even if everything is declared in the same file... right?
    g
    s
    • 3
    • 7
  • e

    ec

    01/17/2020, 8:25 PM
    What does kotlin community thinks on this? Continue stuttering like in Java(2nd) or time to stop (1st)?
    Untitled
    c
    g
    d
    • 4
    • 3
  • a

    antonkeks

    01/18/2020, 11:45 AM
    Anyone knows a proper way to make this compile (without unsafe casting)?
    fun <T: Any> register(c: KClass<T>, i: T) {}
    
    fun main() {
      listOf(ArrayList::class, LinkedList::class).forEach { // any different classes here
        register(it, it.createInstance())
      }
    }
    n
    • 2
    • 6
  • m

    Michał Kalinowski

    01/18/2020, 12:22 PM
    how stable is kotlin.time? Can I use it without fear of massive change or rather it's better to use something else 😄
    z
    a
    i
    • 4
    • 4
  • s

    Shan

    01/19/2020, 7:52 AM
    Is there any way to get more info about an internal Kotlin compiler error other than the stacktrace that is printed? Like which line in the project caused the compiler error perhaps?
    j
    l
    • 3
    • 11
  • g

    ghedeon

    01/19/2020, 12:51 PM
    Do I miss something or type inference is confused here? A. Works
    interface I
    
    class Main : Base<MainParam<*>>
    class MainParam<T : I> : BaseParam
    
    interface Base<T : BaseParam>
    interface BaseParam
    B. Doesn't (
    Type argument is not within its bounds
    )
    interface I
    
    class Main : Base<Main.MainParam<*>> {
        class MainParam<T : I> : BaseParam
    }
    
    interface Base<T : BaseParam>
    interface BaseParam
    n
    s
    • 3
    • 3
  • e

    ec

    01/19/2020, 4:05 PM
    So this compiles but doesnt work as I expected at all, why?
    Untitled
    s
    • 2
    • 21
  • m

    Matthieu Stombellini

    01/19/2020, 4:32 PM
    Hello everyone, I am getting a very strange issue when testing my Kotlin code. The following code:
    val lexer = // an instance of LixyLexer, line 180
    val exc = assertFailsWith<LixyException> {
        lexer.tokenize("....")
    }
    assertNotNull(exc.message)
    assert(exc.message!!.contains("token ends"))
    causes this exception:
    java.lang.VerifyError: JVMVRFY027 récepteur incompatible avec la classe déclarante; classe=guru/zoroark/lixy/LixyTest$Lixy incoherent matcher results cause exception (end is too far)$lexer$1, méthode=invoke(Lguru/zoroark/lixy/LixyDslEnvironment;)V, pc=26
    Exception Details:
      Location:
        guru/zoroark/lixy/LixyTest$Lixy incoherent matcher results cause exception (end is too far)$lexer$1.invoke(Lguru/zoroark/lixy/LixyDslEnvironment;)V @26: JBinvokevirtual
      Reason:
        Type 'guru/zoroark/lixy/LixyTest$Lixy incoherent matcher results cause exception (end is too far)$lexer$1$1' (current frame, stack[1]) is not assignable to 'guru/zoroark/lixy/LixyDslEnvironment'
      Current Frame:
        bci: @26
        flags: { }
        locals: { 'guru/zoroark/lixy/LixyTest$Lixy incoherent matcher results cause exception (end is too far)$lexer$1', 'guru/zoroark/lixy/LixyDslEnvironment', '[Z' }
        stack: { 'guru/zoroark/lixy/LixyDslEnvironment', 'guru/zoroark/lixy/LixyTest$Lixy incoherent matcher results cause exception (end is too far)$lexer$1$1' }
    	at guru.zoroark.lixy.LixyTest.Lixy incoherent matcher results cause exception (end is too far)(LixyTest.kt:180)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        (...snip...)
    However, I am unable to replicate this on my CI environment, everything works fine there... Any ideas?
    a
    • 2
    • 1
  • l

    Luke Sleeman

    01/20/2020, 7:04 AM
    Did I imagine it, or is there some way to build a list using the Function literals with receiver, like typesafe DSLs do, so you can do something like this:
    val myList = listOf {
        add("Blah")
        add("Foo")
        if(somethingIsTrue) {
             add("More")
             add("Stuff")
        }
    }
    I seem to remember somebody talking about it, or tweeting about it? Possibly it was coming to the standard libraries?
    t
    c
    s
    • 4
    • 4
  • b

    bum

    01/20/2020, 11:36 AM
    Is there any different between
    top level variable
    and
    local variable
    ?
    val outer = 1
    
    fun main() {
        val inner = 2
        
        println(::outer.name) // outer
        println(::inner.name) // [References to variables aren't supported yet]
    }
    I'm confused why
    println(::inner.name)
    throws error 😕
    s
    • 2
    • 2
  • s

    Sagar Suri

    01/20/2020, 12:21 PM
    OOP design question: Problem: I have a GOD class in my project which consist of more than 40 to 50 functions which belongs to different services. What I want to achieve: I want to move unique functions to dedicated subclasses and common functions to a parent class. Now the GOD class is injected in many classes. Can someone suggest me a design pattern where I don’t have to individually inject all these
    SubClass
    but a factory which will give the instances of these
    SubClasses
    and also provide access to the common functions which are in the parent class. Is it possible?
    class GodClass {
        fun common(){}
        fun a(){}
        fun b(){}
        fun c(){}
        fun d(){}
    }
    
    abstract class ParentClass {
       fun common(){}
    }
    
    class SubClass1: ParentClass {
        fun a(){}
    }
    
    class SubClass2: ParentClass {
        fun b(){}
        fun c(){}
    }
    b
    e
    • 3
    • 5
  • k

    Kroppeb

    01/20/2020, 12:24 PM
    Should the thing mentioned here be reported as a bug? https://stackoverflow.com/questions/59822125/kotlin-variable-initialization-for-child-class-behaves-weird-for-initializing-va
    👍 1
    🤔 1
    i
    k
    • 3
    • 4
  • s

    steenooo

    01/20/2020, 1:12 PM
    I believe the Jvm kotlin compiler can target 8, right? Are there any plans to target more "modern" versions anytime soon?
    d
    s
    +2
    • 5
    • 8
  • r

    rrva

    01/20/2020, 3:06 PM
    Did anyone integrate a kotlin REPL into one of their apps, for debugging state of an application?
    c
    • 2
    • 3
  • w

    Wesley Acheson

    01/20/2020, 4:20 PM
    whats the best way to chain null checks. Say I had the following
    val configuration = if (config != null) config else
            {
                val retrieved = configRepo.findByMerchantId(id)
                if (retrieved != null) retrieved else MerchantBillConfig(id, emptyList(), CurrencyIso("XXX"), false)
            }
    I mean if a value is passed use that else try to retrieve one else generate a default one.
    w
    d
    • 3
    • 4
  • k

    kyleg

    01/20/2020, 11:38 PM
    kotlinx.coroutines.async(context, start, block)
    appears to be deprecated. What am I supposed to replace it with? I want to put
    async(start=LAZY) { someSuspend() }
    in my code, but I also don’t want to use deprecated functions. Technically I’m updating some third-party library’s documentation, and I’d rather my PR not use deprecated methods. The current sample code uses
    async {…}
    and I’d rather not dramatically alter the sample code, but hew closely to the original.
    s
    • 2
    • 1
  • g

    Gyuhyeon

    01/21/2020, 2:28 AM
    I am very confused. I'm trying to override a spring batch provided class method, but it is having signature issues. I am not sure, but I'm assuming I'm supposed to return null when null otherwise it's not up to spec(perhaps "" will work, but that's not the cleanest solution). Why won't it let me make it a nullable String, when the method it is overriding is java.lang.String in a java source code? How do I get around this? (parameter being nonnull string is also another signature issue - if I make it a nullable string, it says it has nothing to override because of signature mismatch, yet... source reveals it's a plain java string that isn't annotated otherwise)
    k
    s
    m
    • 4
    • 5
  • v

    Vitali Plagov

    01/21/2020, 9:09 AM
    I have a data class with some fields of enum type and some are just Strings. I need to create an object with just one String field and thus not include enum fields. How should I declare enum fields in my data class so that they will have an empty default value?
    z
    • 2
    • 3
  • l

    LastExceed

    01/21/2020, 11:17 AM
    when should i use a type alias, when an inline class and when just the underlying type? example: i'm developing something like an instant messager and each message has a unique ID (which at the end of the day is just a
    Long
    ) and i figured it might be worth using a typealias or inline class to clarify that using this number for e.g. multiplication makes no sense. if possible, I am looking for a generalized answer so I know how to make this decision myself in the future
    a
    r
    m
    • 4
    • 15
  • g

    Gurupad Mamadapur [FH]

    01/21/2020, 11:40 AM
    Is there a way to easily switch between different versions of the Kotlin plugin. Say I want to test out a plugin in EAP channel and then revert to a stable channel plugin. Right now will have load plugin from disk to downgrade.
    i
    a
    • 3
    • 9
  • v

    Vitali Plagov

    01/21/2020, 11:47 AM
    What collections extension function can I use if I want to get first element from the list and if list is empty, then run a function that creates an element and returns it? The closest I found is
    ifEmpty{}
    , but it returns the entire collection if it is not empty, while I don’t need the collection and just it’s first element.
    g
    • 2
    • 2
  • l

    LastExceed

    01/21/2020, 12:09 PM
    is there any proper way to create abstract factory functions to force their implementation? I have an abstract class
    Packet
    (for networking) that needs a
    serialize
    and
    deserialize
    function. the former is easy, just a regular abstract function with a
    ByteWriteChannel
    param to write the packet into. the latter however needs to be either a top-level extension function for
    ByteReadChannel
    or in the companion object, neither of which allows the
    abstract
    keyword (obviously). how do I ensure that each
    Packet
    class implements a
    deserialize
    factory function ?
    n
    • 2
    • 2
  • j

    Jérôme Gully

    01/21/2020, 12:46 PM
    Any documentation or information on writing SDK ? Patterns, architecture, best pratice...
    r
    • 2
    • 1
  • s

    sbyrne

    01/21/2020, 1:45 PM
    In Java I can print terminal control chars like
    System.out.print("\033[100D")
    . Kotlin does not like
    \033
    , how do I do that?
    r
    l
    • 3
    • 4
Powered by Linen
Title
s

sbyrne

01/21/2020, 1:45 PM
In Java I can print terminal control chars like
System.out.print("\033[100D")
. Kotlin does not like
\033
, how do I do that?
r

ribesg

01/21/2020, 1:46 PM
\\033
l

LastExceed

01/21/2020, 1:48 PM
\0
is an illegal escape. either escape the escape character as demonstrated above, or use a literal string
"""\033"""
s

sbyrne

01/21/2020, 1:57 PM
\\
gives me a literal
\
.
\u001b
does what I want.
Oh, I get it. In Java,
\0...
means octal. Kotlin doesn't do that.
View count: 2