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

    Quazi Irfan

    03/25/2022, 7:06 PM
    Is it possible to use compose multiplatform without Kotlin? I am a Java programmers interested in this library.
    m
    j
    6 replies · 3 participants
  • n

    Nathan Kleinschmidt

    03/27/2022, 3:04 PM
    I’m looking for help importing a gradle dependency from a github repo. It looks like I would clone the package code into my project and then reference it in my build.gradle.kts using
    implementation(files(./dependency))
    . My question is which path exactly do I need to reference?
    j
    v
    +1
    13 replies · 4 participants
  • j

    Jan

    03/27/2022, 3:06 PM
    I have a question: I have a client for some database thing and I want to make it easy to extend it. I don't want to use extension functions directly because it would make things a little bit messy. (E.g: Some functions might have the same name but different functionality and that would lead to stupid function names). So I thought it would be better if I split these functions into modules so each module has its associated functions: client.moduleName.associatedFunction() The "moduleName" is a extension property. Now the problem is the associatedFunction() always needs the original client. Thats why I cant make the module an object. But creating a instance of this Module every time someone calls it (with the client as parameter), is also not good. Any idea on how to improve that?
    1 reply · 1 participant
  • l

    LastExceed

    03/28/2022, 10:34 AM
    any1 know a more elegant way to prevent the trailing delay?
    repeat(10) {
        foo()
        delay(500) //problem: causes trailing delay
    }
    i could of course do this:
    foo()
    repeat(10) {
        delay(500)
        foo()
    }
    but it looks kinda ugly to me
    p
    m
    +2
    12 replies · 5 participants
  • n

    Nicolai

    03/29/2022, 6:41 AM
    Hi all 👋 Hope one of you can help me 🙂. I get a list of 'Action's and the actionType inside to define which type of object it should be. For example a FuxiNotification. They are very similar but FuxiNotification will not have all the same parameters but many of them. Likewise any additonal actionTypes would have some but not all.
    data class Action(
        val actionGuid: String,
        val actionType: String,
        val allowClose: Boolean,
        val body: String,
        val deepLink: String,
        val deepLinkId: String,
        val deepLinkSubId: String,
        val deepLinkText: String,
        val fuxiActionVersion: Int,
        val imageUrl: String,
        val isAutoClose: Boolean,
        val isDeleteFromCache: Boolean,
        val isHidden: Boolean,
        val isShowClose: Boolean,
        val pageId: String,
        val questions: List<Any>,
        val submitText: String,
        val submitUrl: String,
        val surveyId: String,
        val theme: String,
        val title: String,
        val validFromUtc: String,
        val validToUtc: String
    )
    and another data class
    @kotlinx.parcelize.Parcelize
    data class FuxiNotification(
        val actionGuid: String,
        val actionType: String,
        val allowClose: Boolean,
        val body: String,
        val deepLink: String,
        val deepLinkId: String,
        val deepLinkSubId: String,
        val deepLinkText: String,
        val fuxiActionVersion: Int,
        val imageUrl: String,
        val isAutoClose: Boolean,
        val isDeleteFromCache: Boolean,
        val isHidden: Boolean,
        val isShowClose: Boolean,
        val pageId: String,
        val theme: String,
        val title: String,
        val validFromUtc: String,
        val validToUtc: String
    ) : Parcelable
    What would be the way to do this in a smart way so I can map Action to FuxiNotification easily? 🙏
    ☠️ 1
    d
    m
    3 replies · 3 participants
  • v

    Vitali Plagov

    03/29/2022, 12:50 PM
    How can I do the same with Kotlin? I want to create a predicate based on the function:
    // java
    var words = List.of("one", "two", "three");
    Function<Integer, Predicate<String>> lengthFun = (minLength) -> (str) -> str.length() > minLength;
    Predicate<String> isLongerThan2 = lengthFun.apply(2);
    Predicate<String> isLongerThan3 = lengthFun.apply(3);
    
    var longerThan2 = words.stream().filter(isLongerThan2).collect(Collectors.toList());
    var longerThan3 = words.stream().filter(isLongerThan3).collect(Collectors.toList());
    I know that these predicates are pretty straightforward and can be inlined straight into the
    filter { }
    function. But I’m more interested in a general approach of how to do it.
    h
    r
    9 replies · 3 participants
  • c

    Comic Playz

    03/29/2022, 2:00 PM
    That is where the serializer is actually being used
    :thread-please: 3
    t
    r
    +1
    25 replies · 4 participants
  • c

    chansek

    03/29/2022, 6:04 PM
    Any possibility to make the below code compilable:
    abstract class SomeLibraryClass<T> {
        abstract fun test(key: String): T
    }
    
    class Item<T : Enum<T>> : SomeLibraryClass<T>() {
        override fun test(key: String): T {
            return enumValueOf(key)
        }
    }
    Can't make T as
    reified
    or
    test
    as inline. How can I inherit the library class for enum?
    c
    2 replies · 2 participants
  • k

    Kamila

    03/29/2022, 6:30 PM
    Hi Guys, please advice. I have a data class with this property
    val bankAccount: BankAccount? = null
    When I parse it to DTO object, which takes bankAccount as String, I use
    bankAccount.toString()
    which, in case of null, ends up being “null” String on DTO object. How should I approach it, so the value is actually null or property is omitted?
    j
    2 replies · 2 participants
  • t

    Tomas Kormanak

    03/30/2022, 9:34 AM
    Hi, is there a way to define private setter for property defined in constructor param? I need something like this, but because of
    @Seriazlizable
    annotation constructor can not have parameter which is not property
    @Serializable
    class Document(
        name: String,
    ) {
        var name: String = name
            private set
    }
    s
    k
    +1
    4 replies · 4 participants
  • c

    César

    03/30/2022, 12:46 PM
    hi! how do I achieve this?
    val courses: Collection<Course> = gson.fromJson(response.string(), Collection<Course>::class.java)
    (the
    Collection<Course>::class.java
    part)
    p
    k
    6 replies · 3 participants
  • p

    poohbar

    03/30/2022, 5:03 PM
    i am doing a bunch of:
    val value = if (someCondition) {
      // compute value
    } else {
      null
    }
    the else branch is always just
    null
    .. is there a more idiomatic way to write this?
    j
    e
    10 replies · 3 participants
  • m

    Matt Yokan

    04/01/2022, 2:47 AM
    Are there any good options for syntax highlighting Kotlin code for the web? We're working on some documentation and wondering if there are any decent options. We were investigating the concept of trying to precompute them with our doc workflow by somehow using the syntax highlighting system used by IntelliJ (we looked at trying to take advantage of the related text framework) but with no luck. Has anyone had any luck in this regard?
    e
    1 reply · 2 participants
  • j

    Jukka Siivonen

    04/01/2022, 9:29 AM
    Noob question about sealed classes usage, what am I missing here
    t
    r
    +1
    10 replies · 4 participants
  • j

    Jukka Siivonen

    04/01/2022, 10:19 AM
    Another question about constructor usage in data classes, is something like this possible without cycle error?
    j
    7 replies · 2 participants
  • h

    hfhbd

    04/01/2022, 5:21 PM
    Hey, I know Kotlin 1.6.20 is not officially released, but it is already uploaded. The Gradle plugin at https://plugins.gradle.org/m2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.6.20/ and Multiplatform https://plugins.gradle.org/m2/org/jetbrains/kotlin/multiplatform/org.jetbrains.kotlin.multiplatform.gradle.plugin/1.6.20/org.jetbrains.kotlin.multiplatform.gradle.plugin-1.6.20.pom are working, but the jvm plugin does not https://repo.gradle.org/ui/native/jcenter/org/jetbrains/kotlin/jvm/org.jetbrains.kotlin.jvm.gradle.plugin/1.6.20/org.jetbrains.kotlin.jvm.gradle.plugin-1.6.20.pom
    🎉 2
    d
    3 replies · 2 participants
  • d

    Damiano Petrungaro

    04/02/2022, 12:22 AM
    I’d love if some of you would give me some feedback about this project I am doing just as a server for practicing Kotlin 🙂 Let me know if you spot any bad practice in the source code, happy to receive some constructive feedback!
    k
    s
    10 replies · 3 participants
  • a

    andodeki

    04/02/2022, 1:39 AM
    Hey guys: I to access individual items in ItemList but i am getting below as output how can i list only "Name1" and "Name2" from "defaultItems"
    [Item(int=1, item=Category1, ItemList={Name=[]})]
    null
    data class Item(
        	var int: Int,
            var item: String,
            var ItemList: Map<String, List<Item>>
        )
        var defaultcategory = listOf(
            Item(1, "Category1", mapOf("Name" to listOf<Item>()))
        )
        var defaultItems = listOf(
            Item(1, "Item1",mapOf("Name1" to defaultcategory)),
            Item(2, "Item2",mapOf("Name2" to defaultcategory))
        )
        
        defaultItems.forEachIndexed { index, element ->
        	print(element.ItemList["Name1"])
            print("\n")
        }
    s
    1 reply · 2 participants
  • m

    Mark

    04/02/2022, 4:09 AM
    When calling
    String.replace(String, String)
    does it ever make sense to wrap it with
    if (String.contains(String))
    for example if the occurrence is very unlikely? Or perhaps it depends on the target architecture?
    s
    e
    +2
    5 replies · 5 participants
  • j

    Junjie Wu

    04/02/2022, 2:00 PM
    Does any one have any idea why the following code prints
    4
    instead of
    13
    ?
    fun add(a: Int, b: Int, cumulate: (Int) -> Unit): Int {
        cumulate(a + b)
        return a
    }
    
    fun main() {
        var answer = 0
        answer += add(4, 5) { answer += it }
        println(answer)
    }
    my guess is that
    answer += x
    equals to
    answer = answer + x
    where the second answer equals to 0, but I can’t find any prove on doc
    j
    9 replies · 2 participants
  • a

    Asq

    04/02/2022, 2:28 PM
    is there a manner to use a type variable ("generic", in this case
    W
    in the example below) with more than one constraint, if a class delegates some of its implementation details? e.g.
    class DirectedEdgeWeighted<W> private constructor (val de: DirectedEdge, val w: W, val wAccretion: (W, W) -> W): DirEd by de where W: Any, W: Comparable<W> { ... }
    produces syntax errors, even after trying several permutations in how the part after the constructor is declared, and before the beginning (say,
    data class
    ) too. It is important that
    DirectedEdgeWeighted
    is-a
    DirEd
    but not is-a
    DirectedEdge
    so inheritance is not a solution.
    This issue is interesting on the basis of syntax principles, so please let's ignore the possibility of making inheritance feasible. I could hypothetically drop
    W: Any
    as a workaround, yes, but a workaround is not the goal of the answer that I seek. Reassuming, without the example above: my question is: is there a manner to use a type variable ("generic") with more than one constraint, if a class delegates some of its implementation details? Thanks for your kind and analytical interest 🙂
    y
    4 replies · 2 participants
  • t

    TwoClocks

    04/02/2022, 9:36 PM
    is there some magic to use JDK modules / incubator code from kotlin? I can write the code, and idea understands it, but I get
    Unresolved reference
    when building (either in idea, or gradle)
    4 replies · 1 participant
  • k

    Kevin

    04/04/2022, 4:06 AM
    Hi, recently i was learning on how to make custom views and i'm found out of the resources which using the method to inflate other views(from other xml activity). after trying it out to referencing the custom views in
    activity_main.xml
    in form of
    <com.test_project.library.buttons.TestButton/>
    , it did works perfectly, but i found out that i cannot override the text value because the
    android:text
    doesn't appear from suggestion. is this because the effect from inflating the views? or there is something that missing from the custom views class that i didn't declare it first so i cannot put text value in
    activity_main.xml
    ?
    r
    3 replies · 2 participants
  • k

    Kamila

    04/04/2022, 7:19 AM
    Hi guys, topic of transforming domain objects into Dto (or enything else), I know I can do something like:
    class Something(val name: String) {
        companion object {
            fun toDto(): Dto(name)
        }
    }
    
    data class Dto(val name: String)
    But I would prefer to have possibility to write:
    Dto.from(foo: Something) = Dto(name = foo.name)
    Is it possible?
    k
    j
    29 replies · 3 participants
  • l

    LastExceed

    04/04/2022, 11:28 AM
    val buffer = ByteBuffer.allocate(4450)
    intellij says the inferred type of this is
    val buffer: (ByteBuffer..ByteBuffer?)
    what does that mean? this isn't even valid code when i try to type this out myself. the code compiles fine on my machine, but jitpack.io fails because of a type mismatch. what is going on here?
    m
    s
    +2
    18 replies · 5 participants
  • j

    Joe

    04/04/2022, 8:09 PM
    We're getting a new warning in 1.6.20 when overriding a deprecated interface method:
    This declaration overrides deprecated member but not marked as deprecated itself. This deprecation won't be inherited in future releases. Please add @Deprecated annotation or suppress
    . This warning didn't occur in 1.6.10 and don't see mention of it in the release notes. is this expected? (we can suppress/remove the warning ok, but build with -Werror so this is backwards incompatible for us)
    m
    1 reply · 2 participants
  • s

    Serena Xu

    04/05/2022, 2:11 AM
    Hi, I am new to Kotlin. I have an API expected request like this:
    @Json(name = "order_id") val orderId: Int,
    @Json(name = "new_delivery_window_id") val newDeliveryWindowId: Int?,
    @Json(name = "new_delivery_window_uuid") val newDeliveryWindowUUID: UUID?,
    @Json(name = "new_delivery_address_id") val newDeliveryAddressId: Int?,
    @Json(name = "otc_items") val otcItems: List<CartOTCItem>?,
    @Json(name = "fills") val fills: List<PrescriptionFulfillment>?,
    @Json(name = "promo_items") val promoItems: List<PromoItem>?,
    @Json(name = "reason") val reason: String?,
    @Json(name = "note") val note: String?,
    @Json(name = "subtotal") val subtotal: Int?
    My payload is:
    {
      "order_id": 980,
      "new_delivery_window_id": 14,
      "new_delivery_window_uuid": "8d",
      "new_delivery_address_id": 136,
      "note": "testing note",
      "subtotal": 1000,
      "reason": "testing reason"
    }
    I got error:
    com.squareup.moshi.JsonDataException: Expected an int but was NULL at path $.createdBy
    . I am a bit confused of
    createdBy
    . Anyone has any clues on this ?
    r
    g
    3 replies · 3 participants
  • z

    zokipirlo

    04/05/2022, 10:36 AM
    Is it possible to somehow call function in different interfaces to combine all results? How to implement
    toMetadata
    to call all
    buildMetadata
    function and merge lists?
    interface Meta {
        fun buildMetadata(): List<String>
    }
    
    interface FeatA : Meta {
       override fun buildMetadata(): List<String> = listOf("A")
    }
    
    interface FeatB : Meta {
       override fun buildMetadata(): List<String> = listOf("B")
    }
    
    class ObjC: FeatA, FeatB {
        override fun buildMetadata(): List<String> = emptyList()
        fun toMetadata(): List<String> // //What to do here to combine all lists (metadata) from interfaces?
    }
    
    fun main() {
        val c = ObjC()
        println(c.toMetadata()) // expecting ["A", "B"]
    }
    e
    1 reply · 2 participants
  • k

    Kenneth

    04/05/2022, 10:57 AM
    Probably more a intellij question than kotlin, but is there a function to detect all full path
    <http://com.my|com.my>.package.MyClass
    in code? I refactored some packages and it got a bit messy, want to change it back to only MyClass.
    j
    v
    10 replies · 3 participants
  • n

    Nowon Lee

    04/05/2022, 4:25 PM
    Excuse me. Can I find resources of Spring Boot with Kotlin? Tutorials in official documentations help me set up Spring Boot applications. I want to get the full content covering the overall process of Backend API development with Kotlin. Thanks.
    s
    1 reply · 2 participants
Powered by Linen
Title
n

Nowon Lee

04/05/2022, 4:25 PM
Excuse me. Can I find resources of Spring Boot with Kotlin? Tutorials in official documentations help me set up Spring Boot applications. I want to get the full content covering the overall process of Backend API development with Kotlin. Thanks.
s

Stephan Schroeder

04/06/2022, 6:54 AM
the overall process (past the setup stage) is identical to Spring with Java. With the added benefit of nullability. Rarely it can be benifitial to know Kotlin's JVM annotations to make the output of your Kotlin code match what would have been used in Java https://www.baeldung.com/kotlin/jvm-annotations
View count: 3