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
getting-started
  • c

    CLOVIS

    10/26/2022, 7:48 PM
    The documentation of the contract
    callsInPlace
    reads "A function declaring the callsInPlace effect must be inline." Yet,
    withContext
    (KotlinX.Coroutines) declares a
    callsInPlace
    effect without being inline. Is it a mistake?
  • j

    Joseph S

    10/26/2022, 8:35 PM
    While reading the docs, I came across running kdoctor to check that my environment is set up correctly. I get the following error:
    [x] Cocoapods
    ruby (ruby 2.6.8p205 (2021-07-07 revision 67951) [universal.x86_64-darwin21])
    * System ruby is currently used
    Consider installing ruby 2.7 via Homebrew, rvm or other package manager in case of issues with CocoaPods installation
    ruby gems (3.0.3.1)
    * cocoapods not found
    Get cocoapods from <https://guides.cocoapods.org/using/getting-started.html#installation>
    I tried what was mentioned for a solution to this but it does not seem to work. Any help is appreciated.
    l
    • 2
    • 26
  • j

    Joseph S

    10/26/2022, 9:48 PM
    I’m reading the docs and I came across something called infix function. Is this something like a type setted function? In Java a function is always given a type whether it’d be a data type or just void. Is it similar to the concept that I mentioned?
    l
    s
    • 3
    • 4
  • m

    Matti Viljamaa

    10/27/2022, 7:48 AM
    Anyone know if there's a project that aims to develop an uniform machine learning framework across Android, desktop etc.? It seems that after Kotlin is fixed for Android and after Kotlin can be compiled for the browser and the desktop, then having such libraries in Java, Python or something is pointless.
    • 1
    • 1
  • i

    Ink

    10/27/2022, 9:11 AM
    Hi, I get string:
    id: 123, price: 29,99, isAvailable: true
    I try to get value of those variables:
    val object= string.trim().removeSurrounding("{", "}").split(",").map {
        it.split(":")[1].trim()
    }
    
    val id = productString[0]
    val price = productString[1]
    val isAvailable= productString[2].toBooleanOrNull()
    The problem is
    price
    . It cointains
    ,
    between 29 and 99 and it makes error. How I can avoid dividing price on two parts in that case? I don't want to use
    .
    instead of
    ,
    s
    s
    +2
    • 5
    • 5
  • y

    Yusuf.I

    10/27/2022, 10:13 AM
    how can i add a check which checks if a class from set package is a data class or not and if it is not it throws an error
    m
    • 2
    • 2
  • m

    Matti Viljamaa

    10/27/2022, 7:27 PM
    Anyone have opinion w.r.t. what the state of Kotlin is w.r.t. Golang in the same use cases? I was confused in particular about the mention of Golang having more refined support for concurrency, but I was unsure as to whether this is some fixed feature of the language or whether it could be gained in Kotlin with time. I wonder if Golang is to be thought more as a server language and Kotlin as an end-user language? My initial problem was about thinking why Kotlin cannot be used in the use cases where Golang is used.
    j
    v
    +3
    • 6
    • 11
  • r

    Ruckus

    10/27/2022, 10:00 PM
    Lately I keep running into issues where, if I have a sealed class hierarchy that spans multiple files, I'll randomly get a "class A cannot extend class B" thrown at runtime as soon as the program starts, and It won't go away till I make some non-trivial changes to the offending code. My gut reaction is that it has something to do with incremental compilation, but I have no idea. Has anyone else run into this? Any ideas on how to diagnose it next time it strikes?
  • j

    Joseph S

    10/28/2022, 3:01 AM
    Hi all, I’m trying to create a random generator to generate an element of an Array/List. Found this in the docs:
    val forBreakfast = Random.nextInt(until = 3).let { menu[it] }
    I get most parts of this code except for what does ‘it’ mean in the square brackets? Is it some placeholder variable to represent the generated number or something?
    j
    k
    • 3
    • 5
  • e

    Eric Williams

    10/28/2022, 1:07 PM
    👋 Hello
  • a

    Avi Perl

    10/28/2022, 2:53 PM
    How can I add serialization to a Java class that I am extending? Everything I'm reading online talks about how to handle a situation where a class that you are serializing has a property that is a Java class, but in my case I'm extending a class and want to make it serializable. Thanks!
    l
    • 2
    • 1
  • a

    Adam Cooper

    10/28/2022, 4:12 PM
    I'm wondering if someone can clarify my understanding of backing fields. I have this property defined in an `object`:
    val wordle = Wordle()
            get() {
                if (this.lastWordListRefresh + 1.hours < Clock.System.now()) {
                    return Wordle().also {
                        <http://this.log.info|this.log.info>("Refreshing Wordle state")
                        this.lastWordListRefresh = Clock.System.now()
                    }
                }
                return field
            }
    My understanding was that returning a different value from
    get
    would set the backing field. But it seems that, if
    lastWordListRefresh
    has "expired", it returns a new object once, and then continues using the old backing object for subsequent calls. Is there a way to make it so that the value returned from
    get
    sets the backing field? I essentially want a property that expires, and then lazily refreshes itself.
    d
    • 2
    • 7
  • j

    Joseph S

    10/28/2022, 7:24 PM
    I came across anonymous functions. The docs show some examples like one line expressions or blocks in a function. But I can’t seem to wrap my head around how does anonymous functions get referenced?
    k
    • 2
    • 2
  • j

    Joseph S

    10/28/2022, 7:30 PM
    Or do these functions run as soon as the computer reaches the line?
  • j

    Jonathan Olsson

    10/28/2022, 8:33 PM
    Hi! I have two instances of two different generic types, say A, and B. Via reflection, how do I figure out if A has any arity-1 method that accepts an instance of B as argument?
    • 1
    • 1
  • e

    elect

    10/29/2022, 8:13 AM
    how to enable context receivers? this doesnt seem to work
    tasks {
        withType<KotlinCompile<*>>().all {
            kotlinOptions {
                freeCompilerArgs += listOf("-Xcontext-receivers")
            }
        }
  • t

    Tolga ÇAĞLAYAN

    10/29/2022, 4:34 PM
    model.searchTextProperty().addListener((obs, old, val) -> {
        var empty = val == null || val.isBlank();
        pseudoClassStateChanged(FILTERED, !empty);
        navMenu.setPredicate(empty ? PREDICATE_ANY : region -> region instanceof NavLink link && link.matches(val));
    });
    
    
    public void setPredicate(Predicate<Region> predicate) {
        content.setPredicate(predicate);
    }
    I have such a code block, how can I translate it to kotlin language?
    s
    • 2
    • 4
  • m

    maarten ha

    10/29/2022, 6:28 PM
    Is there a way to create Ical files in kotlin native without creating a library by myself? Trying to understand RFC-5545 but its a bit above my head.
  • l

    Loney Chou

    10/30/2022, 12:17 PM
    Kotlin 1.7.10. I enable
    -Xlambdas=indy
    , but it seems that kotlin compiler still produces Function class.
    fun main() {
        val a = 0
        l { println(a) }
    }
    
    fun l(block: () -> Unit) {
        block()
    }
    Will produce:
    NEW test/TestMainKt$main$1
    
    public final static l(Lkotlin/jvm/functions/Function0;)V
    
    final class test/TestMainKt$main$1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function0
    c
    • 2
    • 3
  • e

    Ellen Spertus

    10/31/2022, 4:38 AM
    What's wrong with this call to
    fold
    , which causes IntelliJ to give me a very odd suggestion?
    Untitled.kt
    s
    m
    p
    • 4
    • 7
  • s

    Shumilin Alexandr

    10/31/2022, 11:03 AM
    Hi! 🖐️🏻 please help me slove the problem i have a method with two parameters (java):
    public PushSmsResponse sendPushOrSms(PushSmsRequest pushSmsRequest, PushSmsSendRequest pushSmsSendRequest)
    and now i try to fix test (Kotlin!) :
    whenever(
        pushSmsClient.sendPushOrSms(
            PushSmsRequest().apply {
    
                … some parameters, setters etc.
            },
            any<PushSmsSendRequest>() - problem HERE!
    how can I write Kotlin code for analog from java :
    (ArgumentMatchers.any() as PushSmsSendRequest)
    in java it work’s. Mock method with any object PushSmsSendRequest type, how can i do this in Kotlin?
    k
    • 2
    • 13
  • s

    Sam Stone

    10/31/2022, 2:25 PM
    I am writing the only Geni.com Android app (none are available as of yet), and am working on a feature to compare multiple family trees, based on previous work written to compare two trees (complicated). I started by making a map of diffs between each tree, so the diff of tree x with respect to y can be gotten through
    diffs[x][y]
    . I don't even have clear what the edge cases are in a k-diff (based on k-way merge); with a 2-way diff, a given element is either in left, right, or both (in which case a similarity value is given to represent how similar they are). And how do I represent a k-diff graphically? Some of my thoughts now are along the lines of: find the "added" elements that are only in some lists, and make those green; removed elements that are missing from some lists, and make those red; changed elements, and make those orange. But how do I determine those things? All k elements could be different, and their similarity values could all be different relative to each other.
  • a

    Advitiay Anand

    10/31/2022, 8:09 PM
    Basic question: Are there any web topics to be understood before beginning to learn server-side Kotlin? Also, is Ktor -> Spring Boot a logical learning path, or should I jump straight to Spring Boot? (I'm a Jr. Android developer with almost nil web experience. I would like to be able to possibly transition to a backend role after a couple of years, in case I lose my interest in Android)
    k
    a
    +2
    • 5
    • 11
  • l

    Loney Chou

    11/01/2022, 1:46 AM
    As said in kotlin docs, functions that take value class parameter get mangled to avoid conflict, but if there's no conflict, what's the point to mangle them?
    c
    e
    • 3
    • 4
  • s

    Stephan Schroeder

    11/01/2022, 4:16 PM
    I'm trying to get a SpringBootTest (Spring2.5.4) running after switching to Kotlin (1.7.20). So this is the link with the Java example: https://www.appsdeveloperblog.com/testresttemplate-http-post-example/ This is my code with constructor injection instead of property injection via
    @Autowired
    .
    @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
    class ValidationTest(
        private val restTemplate: TestRestTemplate,
    ) {
        @LocalServerPort
        private val port = 0
    
        @Test
        fun greetingShouldReturnDefaultMessage() {
            Assertions.assertThat(restTemplate.getForObject("<http://localhost>:$port/", String::class.java)).contains("405")
        }
    ...
    }
    Unfortunatle the constructor injection fails before the test is even entered. No ParameterResolver for TestRestTemplate can be found.
    No ParameterResolver registered for parameter [org.springframework.boot.test.web.client.TestRestTemplate restTemplate] in constructor [public de.fhirvalidationserver.ValidationTest(org.springframework.boot.test.web.client.TestRestTemplate)].
     org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [org.springframework.boot.test.web.client.TestRestTemplate restTemplate] in constructor [public de.fhirvalidationserver.ValidationTest(org.springframework.boot.test.web.client.TestRestTemplate)].
    I assumed SpringBootTest would instanciate an instance of TestRestTemplate for me. Was that the mistake or is something else missing?
    i
    • 2
    • 2
  • e

    elect

    11/01/2022, 5:22 PM
    I need to use a super public inline method in a subclass, but this is forbidden:
    Accessing super members from public-API inline function is deprecated
    Which workarounds are available? I'd need to call the following
    class Texture1d : Texture {
       inline fun <reified T> load(..): T = super.load<T>(..) // error
    e
    • 2
    • 4
  • y

    Yusuf.I

    11/01/2022, 6:39 PM
    I am having an issue with Gradle would appreciate some help
  • o

    oday

    11/01/2022, 9:47 PM
    what is the type of this object
    object SomeObject
    ? like by default without appending any type
    f
    j
    +3
    • 6
    • 23
  • i

    Ink

    11/02/2022, 9:27 AM
    How I can get Kotlin's object from Java? When I do:
    CustomObject myObject = CustomObject.INSTANCE;
    I get error
    cannot find symbol CustomObject
    j
    • 2
    • 3
  • j

    Jonathan Olsson

    11/02/2022, 12:23 PM
    What is the difference between
    anInstance.javaClass
    and
    anInstance::class.java
    ?
    s
    • 2
    • 3
Powered by Linen
Title
j

Jonathan Olsson

11/02/2022, 12:23 PM
What is the difference between
anInstance.javaClass
and
anInstance::class.java
?
s

Sam

11/02/2022, 12:46 PM
Not much. I think this SO post covers the key points: https://stackoverflow.com/questions/46674787/instanceclass-java-vs-instance-javaclass
j

Jonathan Olsson

11/02/2022, 12:52 PM
I take it then that ::class.java is preferred over javaClass?
s

Sam

11/02/2022, 12:53 PM
I would say yes 👍 the return type is more correct and the meaning is less likely to be ambiguous or unexpected
View count: 4