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

    Alex Kuznetsov

    04/19/2020, 7:32 PM
    Is there a library that serializes data classes into compilable Kotlin code? Something like this:
    k
    • 2
    • 19
  • t

    Terry Franklin

    04/20/2020, 12:43 AM
    Can annotations be added to parameters of a primary constructor? E.g can I convert this -
    class AddressEntity(
            var address1: String?,
            var address2: String?,
            var city: String?,
            var country: String?,
            var postalCode: String?,
            var stateOrProvince: String?
    ) {...
    to something like this -
    class AddressEntity(
            @Property var address1: String?,
            @Property var address2: String?,
            @Property var city: String?,
            @Property var country: String?,
            @Property var postalCode: String?,
            @Property var stateOrProvince: String?
    ) {
    s
    d
    • 3
    • 4
  • n

    nwillc

    04/20/2020, 4:48 AM
    An esoteric Kotlin feature I stumbled across: https://medium.com/@nwillc/kotlin-class-inherits-from-function-675c71e04ecb
    m
    t
    +2
    • 5
    • 4
  • i

    Ivan Brko

    04/20/2020, 2:34 PM
    Hi all, I am trying to do something and I want to check what would be a idiomatic way to do it: I will simplify the problem here: Let's say I have the following function
    fun getSomeString(): String?
    and I have a function that wraps a String (not String?) in some Response
    fun getResponse(msg: String): Response
    then I have a third function in which I need to return a Response and I am calling the getSomeString, if it returns a String I need to feed it to getResponse, but if it returns null I need to return some ErrorResponse object. Now, I wanted to make this a one liner, but I'm having problems with thinking how to do it It would be great if I could do something like this:
    fun GetResponse: Response = 
      when(getSomeString()) {
        is String message -> getResponse(message)
        else -> ErrorResponse()
      }
    but I can't do this is String message. In my real use-case this is not a String but a data class with a lot of fields, and I could match on all those fields and then recreate the object on the right side of -> but that just doesn't seem right. How would this usually be done in Kotlin? I am used to some other languages where this approach of naming the String would be done in is String message ->...
    b
    j
    +4
    • 7
    • 22
  • a

    Amiedema

    04/20/2020, 9:25 PM
    Hey everyone, I’m working on Alpas, a Kotlin-based web framework that is open source. I’d like to get help to reduce infrastructure costs and I can apply for assistance with DO if I have at least 100 stars on the GitHub repo. Would you be so kind as to give me an assist and star the repo? We are just 11 stars away and your support would be very appreciated! Thanks in advance! https://github.com/alpas/alpas
    ⭐ 6
    i
    • 2
    • 4
  • k

    kenkyee

    04/20/2020, 10:17 PM
    is this a compiler bug (1.3.72)? The objects in the map are the right type but it wants the type of the variable to be more defined?
    Untitled
    d
    b
    a
    • 4
    • 5
  • c

    Chills

    04/21/2020, 6:51 AM
    hi , is there a tool to detect data-races , what : implementing a protocol for my company and it has weird behavior at present.
    d
    • 2
    • 5
  • z

    ZabGo

    04/21/2020, 8:07 AM
    Hello everybody, I am new to Kotlin and this channel so I am not sure if it is the right place the post this: I am testing Kotlin Multiplatform. I want to create a function in androidMain with a argument which is an Activity. But it looks like kotlin does not recognise the type Activity.
    fun foo(bar: Activity){}
    Do I have to add anything in the build.gradle.kts? Thanks for your help.
    d
    l
    • 3
    • 4
  • v

    Vivekpanchal64

    04/21/2020, 9:29 AM
    hello, guys, I am new in kotlin development so happy to hear and to learn more and help others too.
    d
    • 2
    • 1
  • c

    Chills

    04/21/2020, 10:55 AM
    Also can kotlin native run on micro-controller ⁉️
    d
    • 2
    • 2
  • v

    Vitali Plagov

    04/21/2020, 11:33 AM
    Hi. What will be the proper way to create an extension function for an Enum? I saw this question, but I’m not sure if it’s a correct approach to define a extension for an Enum. https://stackoverflow.com/q/35966447
    m
    d
    • 3
    • 20
  • j

    Jakub

    04/21/2020, 2:46 PM
    What’s the best practice to pass member of the class to
    object
    private val processor = DeeplinkProcessor()
    
        object branchListener : Branch.BranchReferralInitListener {
            override fun onInitFinished(referringParams: JSONObject?, error: BranchError?) {
                processor.process(referringParams)
            }
        }
    in that case, I can’t access
    processor
    from object
    BranchReferralInitListener
    d
    • 2
    • 2
  • l

    LeoColman

    04/21/2020, 7:27 PM
    Do any of you disagree with that statement? If so, could you enlighten me?
    c
    b
    +2
    • 5
    • 13
  • s

    SrSouza

    04/21/2020, 8:02 PM
    Hi folks! There is anyway to enforce type using generic? I'm using KPropertyT, V and I want to have a function that receives the
    V
    type only from the KProperty.
    s
    j
    • 3
    • 5
  • s

    Slackbot

    04/22/2020, 12:07 AM
    This message was deleted.
    b
    • 2
    • 2
  • n

    napperley

    04/22/2020, 1:53 AM
    Does the Kotlin slack have a channel where people can discuss anything about Kotlin performance?
    m
    d
    • 3
    • 3
  • u

    user

    04/22/2020, 9:08 AM
    message has been deleted
    👍 7
    ❤️ 1
    😎 1
    :kotlin: 1
    r
    n
    • 2
    • 2
  • i

    iex

    04/22/2020, 9:22 AM
    Hi! Implementing a type safe unix timestamp. I want to make the constructor private (should only be initializable via factory methods) but the
    value
    used in it should be publicly readable:
    @Parcelize
    data class UnixTime private constructor(value: Long) : Parcelable {
    
        companion object {
            fun fromValue(value: Long): UnixTime =
                UnixTime(value)
    
            fun minTimestamp(): UnixTime =
                UnixTime(0)
    
            fun now(): UnixTime =
                UnixTime(Date().time / 1000)
        }
    }
    
    fun UnixTime.debugString() =
        "$value, ${toDate()}"
    
    fun UnixTime.toDate() =
        Date(value * 1000)
    This doesn't compile, and has also a warning in
    private
    . How do I implement it correctly?
    d
    k
    • 3
    • 30
  • g

    gabrielfv

    04/22/2020, 6:23 PM
    Why is that a thing in Kotlin?
    val url = "<https://google.com/>"
    val rgxReplace = url.replace("/".toRegex(), "\\/")
    val strReplace = url.replace("/", "\\/")
        
    println(rgxReplace)  // outputs: <https://google.com/>
    println(strReplace)  // outputs: https:\/\/google.com\/
    r
    v
    • 3
    • 6
  • c

    CLOVIS

    04/22/2020, 6:28 PM
    Out of curiosity, why is this forbidden?
    class Test(
      var test: Int,
        get = test++
        private set,
      val test2: Int
    )
    Is there any reason like a syntax ambiguity, or is it just because it's not ‘clean'?
    d
    s
    • 3
    • 4
  • c

    CLOVIS

    04/22/2020, 6:30 PM
    It would also be nice if we could do document constructor properties with this kind of syntax as well:
    class Test(
      /** Put the documentation comment here */
      val test: Int
    )
    s
    d
    z
    • 4
    • 5
  • m

    Michael Sim

    04/22/2020, 6:56 PM
    Is it necessary to specify the type in this case:
    var x = 10
    var z: Long = x.toLong()
    // or can I just write var z as:
    var z = x.toLong()
    // compiler should be able to infer the type, no?
    s
    • 2
    • 14
  • a

    Antoine Gagnon

    04/22/2020, 8:52 PM
    I couldn’t find anything but is there a way to assign to itself in the constructor of a class ? For the sake of simplification let’s say I have
    class Dog{
        val name:String
        val age:Int
    
        init { this = fetchDogFromSomewhere() }
    }
    
    fun fetchDogFromSomewhere():Dog{ 
       // Things
    }
    Is there some way to achieve this? Right now I’m using a companion method that calls fetchDogFromSomwhere
    s
    c
    j
    • 4
    • 7
  • h

    Hexa

    04/22/2020, 10:01 PM
    What IDE is best for Kotlin development? Intellij Ultimate 2020 is very slow and hogging a lot of cpu for me so thinking of alternatives now
    r
    j
    +3
    • 6
    • 10
  • i

    Isaac Miti

    04/22/2020, 10:25 PM
    Hello everyone, I'm Isaac from Lusaka, Zambia. I'm new to Kotlin programming I got into it some seven to eight months ago. I love the language and want to learn the best practices from experts here. I'm still learning the language. I've been also trying out Kotlin Android develop.
    👋 4
    d
    • 2
    • 1
  • c

    camdenorrb

    04/23/2020, 6:13 AM
    How am I supposed to do this??? This causes a compile time error and I need it for packet handling :c
    d
    • 2
    • 9
  • s

    spand

    04/23/2020, 8:10 AM
    After I made some changes to my gradle build some of the modules are now red in IDEA. How do I find out what the problem is ? (Messages tab is empty; Usually I could expand down to the problem but nothing is red below it)
    d
    • 2
    • 7
  • k

    Kagurazaka Tsuki

    04/23/2020, 9:08 AM
    Hi everyone. Is there any way to load variables from an external Kotlin Script file (.kts) when a Kotlin program is running. I wonder if there are any ways to replace .json/.ini/.yaml/… config format with .kts.
    d
    • 2
    • 3
  • p

    Peter Kucera

    04/23/2020, 11:25 AM
    Hi everyone. I have a question about Kotlin Unsigned types, which are still marked as experimental language feature. Do you think they are feasible for use in a multiplatform Android/iOS project using shared module written Kotlin Native? Thanks.
    d
    • 2
    • 4
  • s

    svenjacobs

    04/23/2020, 12:09 PM
    Hi all, is this the best approach of finding a specific item in a list based on a certain predicate and returning the item's index and value at once?
    list.asSequence().withIndex().find { some predicate }
    s
    m
    • 3
    • 9
Powered by Linen
Title
s

svenjacobs

04/23/2020, 12:09 PM
Hi all, is this the best approach of finding a specific item in a list based on a certain predicate and returning the item's index and value at once?
list.asSequence().withIndex().find { some predicate }
s

streetsofboston

04/23/2020, 12:13 PM
Not sure if
asSequence()
is necessary...
s

svenjacobs

04/23/2020, 12:18 PM
I think
asSequence()
makes sense because then the values are computed lazily. So if the predicate matches the second item of the list out of 500, then only two
IndexedValue
needed to be created and 498
IndexedValue
where never created 🙂
m

marstran

04/23/2020, 12:41 PM
withIndex
on a list actually returns a lazy iterable: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/with-index.html
s

svenjacobs

04/23/2020, 12:43 PM
@marstran No 😉
Sequence
has it's own implementation of withIndex.
m

marstran

04/23/2020, 12:44 PM
Sure, but read the doc. It says "Returns a lazy
Iterable
that wraps each element ...".
s

svenjacobs

04/23/2020, 12:44 PM
Regarding an
Iterable
you're correct, but that's the reason why I convert the list to a
Sequence
first
m

marstran

04/23/2020, 12:44 PM
But you don't need to, because the iterable returned by
list.withIndex()
is just as lazy as the sequence.
It doesn't create the other 498 indexed values.
s

svenjacobs

04/23/2020, 12:46 PM
Ah, now I get what you mean 👍🏼
View count: 4