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

    Big Chungus

    04/07/2021, 9:46 AM
    Looking for open source projects that are using npm-publish gradle plugin. I'd like to build a small showcase section on the plugin repo with sample use-cases out there in the wild.
    r
    • 2
    • 1
  • u

    user

    04/07/2021, 10:23 AM
    Kotlin Plugin 2021.1 Released: Improved IDE Performance and Better Support for Refactorings The newest release of IntelliJ IDEA, version 2021.1, comes with the improved Kotlin plugin. Enjoy an improved developer experience with faster code completion and highlighting, change signatures with better IDE support, benefit from better debugging experience for evaluating properties, and more. Here is what you’ll get by installing the new plugin: Faster code completion and […]
    c
    g
    • 2
    • 10
  • u

    user

    04/07/2021, 10:36 AM
    message has been deleted
    🎉 7
    🔥 5
    😍 1
    👍 1
    c
    a
    n
    • 3
    • 5
  • d

    Dhanya S Pillai

    04/07/2021, 11:45 AM
    Anyone please help..how to resolve this? Overload resolution ambiguity: public open fun <T : Any!> fromJson(p0: JsonElement!, p1: Type!): TypeVariable(T)! defined in com.google.gson.Gson public open fun <T : Any!> fromJson(p0: JsonReader!, p1: Type!): TypeVariable(T)! defined in com.google.gson.Gson public open fun <T : Any!> fromJson(p0: Reader!, p1: Type!): TypeVariable(T)! defined in com.google.gson.Gson public open fun <T : Any!> fromJson(p0: String!, p1: Type!): TypeVariable(T)! defined in com.google.gson.Gson
    r
    c
    • 3
    • 21
  • t

    Toby

    04/07/2021, 1:21 PM
    Any simple solution for creating a runnable (main class set in manifest) kotlin/jvm jar with gradle kotlin dsl? None of the provided templates (in IntelliJ or Gradle) are working.
    j
    v
    r
    • 4
    • 20
  • s

    Stanislav Karakovsky

    04/07/2021, 3:12 PM
    Hi there! Can anyone tell me how to activate the debugger for Kotlin/Native (linux)? Apparently I have incompatible versions provided by JetBrains. I have Latest IDEA 2021.1.
    m
    • 2
    • 2
  • t

    thana

    04/07/2021, 3:42 PM
    Hey, can someone explain me why this compiles?
    fun foo () {
            val map: NavigableMap<String, String> = TreeMap()
            map["key"] = null
        }
    d
    c
    m
    • 4
    • 6
  • m

    Michael Böiers

    04/07/2021, 4:03 PM
    Hey! This seems inconsistent. Does anyone know why? @thana
    import java.util.*
    
    fun compiles() {
        val map: AbstractMap<String, String> = TreeMap()
        map["key"] = null // non-null not enforced (platform type)
    }
    
    fun `does not compile` () {
        val map = TreeMap<String, String>()
        map["key"] = null // non-null enforced? Why? Isn't this also a platform type?
    }
    ➕ 3
    n
    r
    +2
    • 5
    • 14
  • d

    dave08

    04/08/2021, 10:09 AM
    Is this the best way to return
    true
    only if all functions return
    true
    ? (without putting them all on the same line... there's some code in between them)
    var success = func1()
    success = success && func2()
    success = success && func3()
    
    return success
    b
    m
    r
    • 4
    • 14
  • j

    Juke

    04/08/2021, 12:14 PM
    Hey, is there any way to get in contact with a developer experience person at Jetbrains? We use Kotlin with IntelliJ every day but have some performance issues with automatic refactorings. We'd love for someone from IntelliJ to shadow one of our team programming sessions to see if we're using it wrong or if it could provide some useful feedback 🙂
    👍 1
    g
    w
    +6
    • 9
    • 23
  • j

    Justin

    04/09/2021, 3:19 PM
    Anyone know how to check for whether Kotlin Multiplatform project code is being run with the IDEA debugger/console attached? I have a test method that loops with a timeout if it takes too long, but when I leave the time elapsed checker in the loop, my breakpoints never get hit when running/debugging tests in IDEA.
    y
    • 2
    • 2
  • e

    eygraber

    04/09/2021, 6:23 PM
    Why does
    runCatching
    autocomplete to
    kotlin.runCatching
    in the IDE? If I remove
    kotlin.
    it still works fine.
    ➕ 7
    b
    c
    +2
    • 5
    • 5
  • r

    Richard Happe

    04/09/2021, 7:38 PM
    Found something neat/interesting... I have this simple bit of code:
    sealed class SealedTypes {
        companion object {
            val types = setOf(One, Two, Three)
        }
    
        object One : SealedTypes()
    
        object Two : SealedTypes()
    
        object Three : SealedTypes()
    }
    
    class TypeContainer {
        // Whichever type of SealedType this is set to is removed from the types set.
        var theType: SealedTypes = One
    }
    And a test that doesn't really do much:
    @RunWith(AndroidJUnit4::class)
    class ExampleInstrumentedTest {
        @Test
        fun test() {
            // uncomment this and the test will not crash
            // SealedTypes.types
    
            TypeContainer()
            SealedTypes.types.forEach { acceptNonNull(it) }
        }
    
        fun acceptNonNull(value: SealedTypes) {
            // no-op
        }
    }
    test()
    surprisingly crashes with a NullPointerException:
    java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter value
    	at com.personal.ktbugtest.ExampleInstrumentedTest.acceptNonNull(Unknown Source:2)
    	at com.personal.ktbugtest.ExampleInstrumentedTest.test(ExampleInstrumentedTest.kt:20)
    	at java.lang.reflect.Method.invoke(Native Method)
    	...
    e
    • 2
    • 6
  • j

    Jason Jackson

    04/09/2021, 8:21 PM
    anyone come to kotlin from scala or clojure? why did you switch
    b
    r
    +5
    • 8
    • 18
  • e

    elect

    04/10/2021, 2:36 PM
    porting native code to Kotlin, if I want to move a group of elements in an Arraylist up front, what's my best option? C++ uses
    stable_partition
    Move elements for which a predicate is true to the beginning
    *         of a sequence, preserving relative ordering.
    y
    • 2
    • 3
  • g

    george

    04/10/2021, 4:02 PM
    Does Jetpack Compose support Raspberry Pi?
    d
    • 2
    • 1
  • r

    Rikin Marfatia

    04/10/2021, 4:57 PM
    If I wanted to really tax the Kotlin compiler to help simulate long build times, anyone have a good idea of how to do that? I was thinking along the lines of writing a bunch of complex expressions but dunno if there are some alternatives
    n
    v
    a
    • 4
    • 7
  • n

    Nthily

    04/10/2021, 8:14 PM
    Hi there,Can anyone tell me where to ask questions about kotlin code?
    j
    c
    • 3
    • 2
  • a

    Arpan Sarkar

    04/11/2021, 1:12 PM
    java.lang.ClassCastException: kotlin.Unit cannot be cast to kotlin.Result
    when using
    useIR = true
    Kotlin Version : 1.4.32 After upgrading to 1.4.32 all
    runCatching { }
    call are throwing
    java.lang.ClassCastException
    is there any bug or breaking changes in version 1.4.32 ? As an example
    suspend fun connect(clientId: String): Boolean {
            if (isConnected) {
                Timber.d("Already connected to broker ${mqttClient.serverURI}")
                return true
            }
            mqttClient = MqttClient(BuildConfig.BROKER_URI, clientId, null)
            mqttClient.setCallback(mqttCallback)
    
            val result = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                runCatching {
                    Timber.d("Connecting to broker  ${mqttClient.serverURI}")
                    val options = MqttConnectOptions().apply {
                        mqttVersion = MqttConnectOptions.MQTT_VERSION_3_1_1
                        isCleanSession = true
                        isAutomaticReconnect = true
                        maxReconnectDelay = 10000
                    }
                    mqttClient.connect(options)
                    Timber.d("Broker connected.")
                }
            }
            result.exceptionOrNull()?.let { t ->
                Timber.e(t, "Failed to connect to the broker.")
            }
            return result.isSuccess
        }
    r
    • 2
    • 1
  • a

    Ananiya

    04/11/2021, 4:02 PM
    Hello there :)
    kt
    val thisIsATest = "**bold** normal **even bold** normal2"
    
    "\\*\\*([\\s\\S]+?)\\*\\*(?!\\*)".toRegex().replace(thisIsTest,".").let{
    println(it)
    }
    Is there any way to print like
    bash
    .bold. normal .even bold. normal2
    Instead of [the output from the above code]
    . normal . normal2
    n
    • 2
    • 2
  • g

    Grigorii Yurkov

    04/11/2021, 4:52 PM
    Don't you think that 5 rules enumerated in
    equals
    doc are not full? Look at this code:
    class MyClass {
        override fun equals(other: Any?): Boolean {
            return other != null
        }
    }
    1. Reflexive: for any non-null value x, x.equals(x) should return true. ✅ 2. Symmetric: for any non-null values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.✅ 3. Transitive: for any non-null values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.✅ 4. Consistent: for any non-null values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.✅ 5. Never equal to null: for any non-null value x, x.equals(null) should return false.✅ But this code leads to the strange behavior:
    println(MyClass() == Any()) // true
    println(Any() == MyClass()) // false
    r
    v
    +2
    • 5
    • 23
  • j

    Jonathan Mew

    04/12/2021, 11:01 AM
    Is there a way to flag a collection as non-empty to the compiler in the same way you can flag a variable as non-null - or has it already been considered/proposed?
    y
    b
    i
    • 4
    • 3
  • a

    Andrew

    04/12/2021, 2:17 PM
    What's difference and when should each be used? 🤔
    sealed class Fruit
    object Apple : Fruit()
    object Banana : Fruit()
    vs
    sealed class Fruit {
       object Apple : Fruit()
       object Banana : Fruit()
    }
    e
    n
    +3
    • 6
    • 19
  • s

    Sudhir Singh Khanger

    04/12/2021, 3:26 PM
    All these
    build-1.5.20-dev-5029
    makes release page extremely noisy to follow Kotlin's Github release page via RSS.
    👍 1
    a
    • 2
    • 1
  • t

    therealbluepandabear

    04/13/2021, 12:06 AM
    Found a super good question here on SO someone asked: https://stackoverflow.com/questions/67066647/kotlin-what-is-the-point-of-private-variables-inside-private-companion-objects
    t
    n
    y
    • 4
    • 5
  • n

    nickheitz

    04/13/2021, 8:53 AM
    Can anyone recommend a tool that allows you to attach a kotlin repl to an already running JVM process? As the target environment is CLI only, intellij wouldn't be a choice. I'm looking for something like scalive for scala or liverepl for clojure.
    n
    • 2
    • 5
  • m

    Marian Schubert

    04/13/2021, 11:06 AM
    Which Kotlin book should I recommend to my teammate who is going to start with Kotlin? (He has experience with Python).
    b
    k
    +5
    • 8
    • 10
  • y

    Yan Pujante

    04/13/2021, 1:53 PM
    Where do you usually publish your kotlin libraries? On Maven Central (since the sunset of bintray/jcenter)? If so what do you use for publishing? It seems to me to be so overly complicated (pgp signing, staging area, manual intervention...). Has anybody made it simple?
    n
    b
    +2
    • 5
    • 17
  • a

    amirhosen.ebrahimi

    04/13/2021, 3:52 PM
    Hello guys . I have presentation of compose . I looking for good ready powerpoint file . because my time is low
    😬 1
    😀 1
    k
    p
    m
    • 4
    • 3
  • a

    alllex

    04/13/2021, 7:56 PM
    I’ve found a case where type-inference “hides” a compile-time error and turns it into a runtime problem. I have this snippet:
    class Holder<out T>(val make: () -> T)
    fun <T> Holder<T>.test(value: T) = check(value == make())
    
    fun main() {
        val h: Holder<Int> = Holder { 10 }
        h.test("what?") // intuitively, should not compile
    }
    I would expect that this code does not type-check, because I am trying to compare
    Int
    and
    String
    . However, in the call to
    test
    ,
    T
    is inferred to
    Any
    . Which actually allows you to pass any argument whatsoever, and it will compile. The problem is that
    Holder
    class is a library class, that I cannot modify. However, the
    test
    function I can modify, but without changing its signature. Is there a way to make the
    test
    function check that
    T
    is actually the same at the call-site without explicit typing? (
    h.test<Int>("what?")
    ) P.S. Removing
    out
    modifier from the
    Holder
    signature solves the problem, but unfortunately, the
    Holder
    class comes from a dependency.
    m
    • 2
    • 2
Powered by Linen
Title
a

alllex

04/13/2021, 7:56 PM
I’ve found a case where type-inference “hides” a compile-time error and turns it into a runtime problem. I have this snippet:
class Holder<out T>(val make: () -> T)
fun <T> Holder<T>.test(value: T) = check(value == make())

fun main() {
    val h: Holder<Int> = Holder { 10 }
    h.test("what?") // intuitively, should not compile
}
I would expect that this code does not type-check, because I am trying to compare
Int
and
String
. However, in the call to
test
,
T
is inferred to
Any
. Which actually allows you to pass any argument whatsoever, and it will compile. The problem is that
Holder
class is a library class, that I cannot modify. However, the
test
function I can modify, but without changing its signature. Is there a way to make the
test
function check that
T
is actually the same at the call-site without explicit typing? (
h.test<Int>("what?")
) P.S. Removing
out
modifier from the
Holder
signature solves the problem, but unfortunately, the
Holder
class comes from a dependency.
m

mkrussel

04/13/2021, 8:02 PM
So since the
out
is there, `Holder<int> isa `Holder<Any>`Since
Holder<Any>
contains an extension function that can take a
String
everything works. This shouldn't cause any problems. Since T can only be used as an
out
anything that
test
does with the
T
will be limited to
Any?
so the type inference choice should not cause any runtime problems. It might be nice for this to be broken, but I think this behavior is what is desired most of the time.
a

alllex

04/13/2021, 8:16 PM
You are right about the is-a relation with
Holder<Any>
. I guess not much harm is done, because as soon as you try to use the type inferred to
Any
, you start getting compile-time errors. E.g. if
test
would return
value
.
View count: 3