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

    Jérôme Gully

    02/07/2020, 1:51 PM
    if (data in selectedItems) {
        selectedItems.remove(data)
    } else {
        selectedItems.add(data)
    }
    It is a better way to write this type of condition in Kotlin ?
    selectedItems
    is an arraylist and
    data
    is an object of arraylist type
    s
    j
    t
    • 4
    • 5
  • k

    Kroppeb

    02/07/2020, 4:27 PM
    Is it possible to make sure a type parameter is not
    Nothing
    at compile time?
    s
    f
    • 3
    • 20
  • f

    Fleshgrinder

    02/07/2020, 4:46 PM
    So we have
    @JvmSynthetic
    to hide Kotlin functions from Java users, however, we have no equivalent
    @JvmOnly
    (or whatever it would be named) to hide definitions from Kotlin. I tried
    @Deprecated("Java only", level = HIDDEN)
    but it's hidden in Java afterwards as well if you use IntelliJ. 😛 Any known workarounds for this or is a feature request the only possible thing?
    j
    m
    m
    • 4
    • 11
  • f

    fcosta

    02/07/2020, 5:06 PM
    https://snyk.io/blog/kotlin-overtakes-scala-and-clojure-to-become-the-2nd-most-popular-language-on-the-jvm/
    m
    • 2
    • 2
  • g

    gbaldeck

    02/07/2020, 6:10 PM
    c
    f
    +2
    • 5
    • 11
  • k

    kyleg

    02/07/2020, 8:46 PM
    Why does the compiler give me the error
    TypeMismatch
    in the
    onCreateViewHolder
    for both branches of the
    when
    ? Return type is listed as the sealed class
    BaseHolder<PossibleRow>
    and the return types are both subclasses of the sealed class.
    sealed class PossibleRow { /* objects A, B defined here */ }
    
    sealed class BaseHolder<T: PossibleRow>(...): RecyclerView.ViewHolder(...) {
      class AHolder(...): BaseHolder<PossibleRow.A>(...)
      class BHolder(...): BaseHolder<PossibleRow.B>(...)
    }
    
    class LiftGroupRowAdapter {
      override fun onCreateViewHolder(..., viewType: Int): BaseHolder<PossibleRow> {
        return when(viewType) {
          0 -> BaseHolder.AHolder(...)
          1 -> BaseHolder.BHolder(...)
          else -> throw IllegalStateException("invalid viewType")
        }
      }
    }
    j
    • 2
    • 5
  • s

    Sinan Kozak

    02/08/2020, 6:08 AM
    Hey, which channel is best place for giving feedback for kotlin ide plugin 1.3.70-eap-184-Studio-4.0-1p? Specifically about code formatting?
    f
    • 2
    • 1
  • t

    Tmpod

    02/08/2020, 2:01 PM
    Hey! I want to add better shutdown handling to my project by adding hooks to when signals like SIGINT and SIGTERM are sent but I see no way of registering hooks for those. A multiplatform solution would be the best ofc, but a JVM only one suffices for now.
    n
    • 2
    • 1
  • r

    ribesg

    02/08/2020, 7:43 PM
    I updated a 1.3.50 project to 1.3.61 and suddenly
    javaClass.getResourceAsStream
    returns null, any idea? I can see the file in the jar when I open it, I don't know what's happening
    t
    d
    a
    • 4
    • 5
  • s

    Saood

    02/09/2020, 11:06 AM
    Hi Team, I created project on Kotlin Native, I am trying to use iOS pod library in Kotlin native but facing some issue, Can you please have a look on my question on stackoverflow and reply to me here "https://stackoverflow.com/questions/60126503/how-to-add-thirdparty-ios-pod-library-into-kotlin-native-project-getting-error"
    👎 4
    n
    • 2
    • 5
  • s

    Slackbot

    02/09/2020, 12:22 PM
    This message was deleted.
    🤣 1
    :thread-please: 3
    👎 3
    r
    s
    • 3
    • 2
  • y

    Yan Pujante

    02/09/2020, 1:44 PM
    A bit off topic, but I have been trying to use Jetbrains mono font to write some Kotlin code with the Atom editor. I have been looking and looking and can't find a way to turn off ligature (which unfortunately changes the alignment of my code). Any idea how to do that?
    r
    • 2
    • 1
  • a

    Animesh Sahu

    02/09/2020, 2:32 PM
    Somebody tried to build plugin based architecture, how should it be implemented? I thought to make a common interface's repo and then pull it on every plugin and then implement that, then call the core(main) app for adding the plugin and run it. But how should the plugin be restricted to some area, such as protection from potentially destroying or hijacking the core app? Any thoughts on this topic?
    k
    • 2
    • 1
  • c

    Chills

    02/09/2020, 3:57 PM
    whats wrong with this code? why isActive not detecting the cancel https://pastebin.com/UcYmAAJj
    d
    z
    • 3
    • 6
  • r

    Rodrigo Silva

    02/09/2020, 4:07 PM
    Someone who understands callbacks and wants to help with this little problem:
    • 1
    • 1
  • b

    bod

    02/09/2020, 5:09 PM
    Hello, World! Are there known bugs where the Kotlin compiler never ends? I'm in this situation and don't know what to do.
    c
    k
    +2
    • 5
    • 12
  • b

    Bruno_

    02/09/2020, 6:12 PM
    I cannot get my IDEs (AS nor IDEA) to display jdk sources, it shows the decompiled classess (therefore without documentation/highlighting), any idea how to fix that?
    • 1
    • 2
  • k

    ken

    02/09/2020, 10:27 PM
    What does this type mean exactly and in what scenario is it use ? "Function<*, *> means Function<in Nothing, out Any?>."
    s
    • 2
    • 2
  • g

    Gyuhyeon

    02/10/2020, 5:24 AM
    People keep saying that null safety is one of the important design philosophy of kotlin but I have no idea how it applies in real life code:
    /* Case A: java-style */
    val result = repository.select()
    if (result != null) {
        doSomething() // business logic
    } else {
        doSomethingElse() // business logic
    }
    
    /* Case B: Kotlin style...? */
    repository.select()?.also {
        doSomething()
    } ?: run {
        doSomethingElse()
    }
    
    /* Case C: Kotlin style... + better job security through code only the creater can understand? */
    try {
        repository.select()!!.run {
            doSomething()
        }
    } catch (NullPointerException e) { // or whatever it was that catches not null assertion error
        doSomethingElse()
    }
    What is the better solution here? Obviously we can't make repository.select return non nullable type because that will result in an exception anyway. Business logic requires a different action for nonexisting row, and the only way to do this is either catch an exception, use obscure code with
    .also
    and
    ?:
    , or use plain old java style code. Is there any other solution to this?
    🅰️ 2
    n
    f
    +3
    • 6
    • 8
  • c

    camkadev

    02/10/2020, 12:31 PM
    is there anywhere
    kotlinx-serialization
    example for
    protobuf
    on
    jvm
    ?
    s
    • 2
    • 2
  • m

    Madhan

    02/10/2020, 12:49 PM
    is there any image processing library for kotlin? like jimp in node js
    e
    e
    g
    • 4
    • 7
  • r

    Rob Murdock

    02/10/2020, 3:30 PM
    quick general question - is there a good tiny library for getting a human readable representation of the difference between two strings?
    l
    s
    +2
    • 5
    • 7
  • b

    bbaldino

    02/10/2020, 5:05 PM
    Is there a way to constrain the value of an inline class? Say, for example, I wanted to create an inline class
    NonZeroInt
    . I can do something like throw in
    plus
    ,
    minus
    , etc. if the result ends up being 0...but how can I prevent the instance from being initialized with 0? I can't do an init block to verify it, and have to expose the primary constructor. I tried looking at
    UInt
    , which prevents you from assigning a negative number to it, but how does it enforce that? The primary constructor takes in an
    Int
    .
    m
    t
    f
    • 4
    • 16
  • p

    Pablo Schmid

    02/10/2020, 6:01 PM
    Hi, I have an issue with transient fields not being initialized after jpa saves the entity and get the value back. The reason of this is that kotlin is generating a default constructur with no params that calls super() when there is at least 1 constructor field without default value. If I define defaults to all my field in the primary constructor, then kotlin is not generation the default constructor with no params calling super() ans hence my transient field is being initialized well data class Person( var name: String){ @transient private val id: MyId = MyId() // after repo.save(person); this is not being initialized. id is null } fix data class Person( var name: String = “”){ //creating default values fix the problem @transient private val id: MyId = MyId() } Is this a bug?
    r
    • 2
    • 4
  • c

    cak

    02/11/2020, 2:31 AM
    Really loving learning Kotlin, laptop needs a sticker. Anyone know where I can get some Kotlin swag?
    d
    s
    +3
    • 6
    • 7
  • a

    aeruhxi

    02/11/2020, 6:19 AM
    Is there something like Sealed Inline Class?
    k
    f
    j
    • 4
    • 11
  • j

    Jakub

    02/11/2020, 9:19 AM
    I have complex logic in nested foreach loops that is adding items to my collection. It smells that I need to call
    list.add(item)
    everywhere. (I will use simple example) I’ve tried to replace
    (0..3).forEach {
        list.add(it)
    }
    with
    list.add(
        (0..3).forEach {
            it
        }
    )
    However, it doesn’t compile. Is there a way to achieve it?
    j
    s
    f
    • 4
    • 9
  • n

    nitrog42

    02/11/2020, 2:03 PM
    first try
    🎉 8
    🥌 1
    👏 3
    😄 9
    m
    • 2
    • 1
  • e

    Ellen Spertus

    02/11/2020, 7:11 PM
    I have a string template that will be read in from a file, so I can’t do regular $-interpolation on it. For example, the template might be “20+%1+5”, and I will want to substitute a value at run-time for “%1". Should I just use
    String.replace()
    or
    String.format()
    , or is there a more elegant solution in Kotlin than there would be in Java?
    p
    t
    • 3
    • 3
  • m

    Martin Nordholts

    02/12/2020, 8:54 AM
    Why does this Minimal, Reproducible Example print
    null TheValue
    ? I expect it to print
    TheValue TheValue
    enum class EnumClass(val self: EnumClass? = null) {
        TheValue(self = TheValue)
    }
    
    enum class OtherEnumClass(val other: EnumClass? = null) {
        OtherValue(other = EnumClass.TheValue)
    }
    
    fun main() {
        println("${EnumClass.TheValue.self} ${OtherEnumClass.OtherValue.other}")
    }
    s
    d
    +3
    • 6
    • 20
Powered by Linen
Title
m

Martin Nordholts

02/12/2020, 8:54 AM
Why does this Minimal, Reproducible Example print
null TheValue
? I expect it to print
TheValue TheValue
enum class EnumClass(val self: EnumClass? = null) {
    TheValue(self = TheValue)
}

enum class OtherEnumClass(val other: EnumClass? = null) {
    OtherValue(other = EnumClass.TheValue)
}

fun main() {
    println("${EnumClass.TheValue.self} ${OtherEnumClass.OtherValue.other}")
}
s

spand

02/12/2020, 8:56 AM
You cannot reference TheValue enum before it has been initialized
m

Martin Nordholts

02/12/2020, 8:58 AM
Right, but when I do the printing, everything has been initialized. Technically I don’t see why the code shouldn’t behave as I expect. But I guess the current compiler just doesn’t support this.
d

diesieben07

02/12/2020, 9:00 AM
But the
TheValue
constructor does not run when you print, it runs at the class-init time of
EnumClass
, before
EnumClass.TheValue
has been assigned (how can it be assigned, you are in the middle of creating it's value!)
s

spand

02/12/2020, 9:01 AM
It has nothing to do with the compiler. Yes everything has been initialized when you print but when you call the constructor here:
TheValue(self = TheValue)
TheValue has not been thus self is assigned to null
m

Martin Nordholts

02/12/2020, 9:01 AM
Ok maybe my demands are unreasonable. But then at least a compiler warning or maybe even compiler error would be nice 😬 Anyway, thanks for the input.
s

Stephan Schroeder

02/12/2020, 10:11 AM
You’d get your compile-time warnings, if you make the type of the parameter non-nullable. It’s a good idea to try to be non-nullable if possible (e.g. by using
by lazy {..}
to compute values that aren’t available immediately). It pretty much took extra effort (nullable class + default null parameter value) to not make the compiler complain about this 😂
m

Martin Nordholts

02/12/2020, 10:12 AM
Yes the compiler did complain about earlier versions of that code, but after fixing those warnings and not getting new ones, I figured I was good to go 🙂
s

Stephan Schroeder

02/12/2020, 10:14 AM
it was good to go. It did exactly what you definded (but not what you wanted 😉) with a self-value that was
null
to start with.
m

Martin Nordholts

02/12/2020, 10:16 AM
exactly what you definded
I don’t see how you can think that
TheValue(self = TheValue)
is to be interpreted
TheValue(self = null)
s

spand

02/12/2020, 10:30 AM
Not specifically but you always have to be aware of initialization order when running code in the class initializer.
m

Mike

02/12/2020, 12:36 PM
I'm surprised the compiler did anything other than stackoverflow on this. You want to assign the value of
self
in a class to the class itself. But in order to assign it, the class has to be constructed. But in order for the class to be constructed, it needs the pointer to the class. etc, etc, etc... So I'm unsure how you expect it to work. And the above also explains why it wouldn't have compiled if
self
was non-null. But just getting it to compile doesn't always guarantee it will work. We all wish it was that simple 😉
m

Martin Nordholts

02/12/2020, 12:40 PM
I expected the compiler to produce the equivalent (not in the literal sense, but I think you get my point) of this code:
enum class EnumClass(var self: EnumClass? = null) {
    TheValue();
}

enum class OtherEnumClass(val other: EnumClass? = null) {
    OtherValue(other = EnumClass.TheValue)
}

fun main() {
    EnumClass.TheValue.self = EnumClass.TheValue
    println("${EnumClass.TheValue.self} ${OtherEnumClass.OtherValue.other}")
}
that code runs just fine.
d

diesieben07

02/12/2020, 12:42 PM
But that's not what you told the compiler to do. You told the compiler to read the value of
TheValue
at the point where you construct
TheValue
, in the initializer of
EnumClass
.
☝️ 1
m

Martin Nordholts

02/12/2020, 12:44 PM
I told the compiler to have an enum value field reference itself. That end result is demonstratably possible ☝️
d

diesieben07

02/12/2020, 12:46 PM
That's not how the Kotlin compiler works...
m

Martin Nordholts

02/12/2020, 12:46 PM
Yes my friend, I’ve noticed that 🙂
m

Mike

02/12/2020, 12:47 PM
You need to take a step back, and 'think like the machine' when you run the code. In your second example, The
TheValue
object gets created as soon as
EnumClass.TheValue
is executed. This will initialize the object, assign it in memory. And since
self
is nullable AND has a default value, all is good. Now the compiler will execute the assignment of
self
within
TheValue
, and it has an object to point to. This works ONLY because enums are singletons. When you try to combine it, you put the compiler into a stackoverflow situation as described above. Hopefully that helps you conceptualize it.
m

Martin Nordholts

02/12/2020, 12:50 PM
Thanks for taking the time to explain it. I feel (and felt for a while now) that I understand why this is happening. I just don’t think it’s intuitive. But hey, it’s not the end of the world. You adapt your code and move on. I get that the current behavior is defendable.
m

Mike

02/12/2020, 1:57 PM
These are the hard parts of programming. Often what seems reasonable to our human mind can't be accomplished (yet) by the compiler. The compiler could achieve internally, what you effectively did with a few lines of code, BUT then we'd complain even more that the compiler is too slow ;(
i

ilya.gorbunov

02/12/2020, 10:18 PM
I believe this case of enum entry self-reference should be clearly identifiable by the compiler as an error. I've added this case to the similar issue https://youtrack.jetbrains.com/issue/KT-20662
👍 2
View count: 3