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

    matt tighe

    06/12/2020, 9:16 PM
    Let’s say I want to define a data class over a generic type, as part of a sealed class so that I can use it like this
    when (result) {
        is SuccessDataClassWithGenericTypeOf<MyGenericType> -> doThings(it)
        is Failed -> doFailedThings(it.failureMessage)
        is Loading -> doLoadingThings
    }
    Why does the type get erased in this case:
    sealed class MyResultType {
        data class SuccessDataClassWithGenericTypeOf<T>(val result: T) : MyResultType()
        object Loading : MyResultType()
        data class Failed(val failureMessage: String) : MyResultType()
    }
    But not in this case:
    sealed class MyResultType<out T> {
        data class SuccessDataClassWithGenericTypeOf<T>(val result: T) : MyResultType<T>()
        object Loading : MyResultType<Nothing>()
        data class Failed(val failureMessage: String) : MyResultType<Nothing>()
    }
    k
    • 2
    • 1
  • a

    Alexey Demedeckiy

    06/13/2020, 6:59 PM
    Hi! I am trying to implement some sort of event store / redux store using corutines in android application Here is the pseudocode:
    class Store {
      private val channel = Channel<Action>()
      
      suspend func dispatch(action: Action) {
        channel.send(action)
      }
    
      init {
        GlobalScope.launch {
          for (action in channel) {
            reduce(action)
            notifyObservers()
          }
        }
      }
    }
    Sadly, this code doesn't work - actions are not reducer. Small detail: If i will explicitly set Dispatchers.Main in init and in dispatch - it work, but defeats my purpose. My goal is to move action processing of main thread.
    notifyObservers
    will build
    Props
    for each active
    ViewModel
    and publish.
    h
    n
    • 3
    • 2
  • h

    harry.singh

    06/17/2020, 2:16 PM
    Hi! I'm learning Coroutines and trying to wrap my head around how coroutines are run on a thread. So if I run large number of work-heavy coroutines on a thread, it will block that thread but if I run handful of them, there's a very small probability that the thread will be blocked. I'm trying to understand, how and why does coroutines block the thread in the former case and not in the latter one?
    a
    a
    • 3
    • 20
  • m

    matt tighe

    06/17/2020, 9:37 PM
    is it possible to configure an object in a sealed class to execute some behavior any time it is accessed? e.g.
    sealed class ErrorStates {
        object ThingsAreBadNow {
            onAccess {
                Logger.log("A bad thing happened")
            }
        }
    }
    The
    init
    block can be used for data classes. Is there something I can do to get a similar behavior for objects?
    c
    • 2
    • 5
  • t

    Tony Blundell

    06/18/2020, 8:54 PM
    Hi, is anyone able to help me with the correct syntax here please? I have the following class, which basically gets a JSON string from AWS, then converts it to an instance of a data class...
    class SecretsManager(region: String) {
        private val gson = Gson()
        private val smClient = AWSSecretsManagerClientBuilder.standard().withRegion(region).build()
    
        fun <T> getSecret(id: String): T {
            val req = GetSecretValueRequest().withSecretId(id)
            val json = smClient.getSecretValue(req).getSecretString()
            return gson.fromJson(json, T::class.java)
        }
    }
    To be used like this...
    val myInstance = SecretsManager("eu-west-2").getSecret<MyDataClass>("myId")
    Currently, I get an error
    Cannot use 'T' as reified type parameter
    . I can get around this by marking the function as
    inline
    and T as
    reified
    , but then I can't access the private attributes from within the function. What's the best way to do this in Kotlin?
    a
    w
    • 3
    • 3
  • w

    Wesley Acheson

    06/19/2020, 11:36 AM
    Simple question about nullable objects. is there a simple way to map them to other objects. Something similar to javas
    Optional<String>.map(...).orElse(null)
    I'm currently writing this
    if (source.mpi.dsEndProtocolVersion!= null) Version(source.mpi.dsEndProtocolVersion!!) else null
    but that doesn't feel right to me. Nullable String to nullable Version
    d
    j
    • 3
    • 27
  • l

    Lqncer

    06/21/2020, 3:12 PM
    Hi everyone, I just joined this Slack and wow its a hidden gem. I had a few questions. Most others say you need to learn Java before you try to learn Kotlin, is this true? My other question is, I have never used Kotlin before, just briefly watched some YouTube videos about it. Does anybody have any suggestions for resources for learning the language or would you guys just build projects to learn? Thanks in advance! 🙂
    d
    e
    b
    • 4
    • 7
  • j

    Joakim Tengstrand

    06/22/2020, 10:26 AM
    Hi! I'm new to Kotlin. Does Kotlin support having more than one src folder?
    r
    • 2
    • 21
  • j

    Joakim Tengstrand

    06/22/2020, 12:46 PM
    I can't get my Gradle DSL integration to work, IDEA doesn't understand that I want to have several src-filders. Any ideas? This is how my gradle.build.kts looks like, that lives on the root of my project:
    plugins {
        kotlin("jvm") version "1.3.72"
    }
    
    buildscript {
        repositories {
            mavenCentral()
        }
    
        dependencies {
            classpath(kotlin("gradle-plugin", version = "1.3.72"))
        }
    }
    
    sourceSets.main {
        java.srcDirs("components/logger/src",
                     "components/user/src")
    }
    d
    m
    • 3
    • 7
  • j

    Joakim Tengstrand

    06/22/2020, 3:02 PM
    Is there anyone here that knows Clojure?
    n
    m
    j
    • 4
    • 10
  • s

    Stefano Longhi

    06/24/2020, 12:46 AM
    Hi all, I’m trying  to add on my build.gradle.kts this command
    buildConfigField("String", apiKey, "123abc")
    but I received this error: “Unresolved reference: buildConfigField ” All the example that I found put the command  in Android{ … } but I’m not doing an android app, only a simple web service. Do you have any idea ho I could resolve the problem? thanks
    m
    r
    • 3
    • 3
  • d

    Della Anjeh

    06/24/2020, 6:53 PM
    Hi everyone! I want to build a Kotlin Multiplatform App so I figured getting my feet wet in open source would be great for learning. Any open source multiplatform Kotlin apps you all know of?
    s
    • 2
    • 2
  • s

    Sean

    06/25/2020, 5:52 PM
    Hi, thanks for the invite! Brief introduction: I have completed a two year diploma, mostly did C# and Java webapp stuff. I just started learning Kotlin a month ago, I'm almost done the Android Kotlin Fundamentals Codelabs. First thing, I'm still a bit confused with the Kotlin syntax... I can comment my tutorial code and know what's happening overall, experience with Java helps here, I understand the idea of Entity classes and data binding etc. But the details of each part of the code still confuse me. This is bad and I want to fix ASAP, would you guys suggest Kotlin koans for this, or maybe the Kotlin bootcamp Codelabs instead? Second, at school we did everything with local databases. I'm trying to build an Android app that saves data online and a webapp that can access this data. On the app side of things, it looks like the Room persistence library sorts out most of my issues, but I could use some more reading material and/or tutorials regarding using it with an online database instead of a local database. Last, where would I be able to find more info on frameworks used for Kotlin web app development? I've been trying to research but I'm pretty unfamiliar with the subject so it's hard for me to find useful information. It looks like ktor or spring boot would be worth considering, am I on the right path here? If someone could point me in the right direction that would be awesome. Apologies if I'm ranting a bit here or if I missed any important information, I can clarify or add information if needed. Thanks for any input :)
    d
    m
    • 3
    • 4
  • t

    Terry Franklin

    06/28/2020, 11:42 PM
    What options exist for converting JSON schemas (not payloads) into Kotlin data classes? I have tested the JsonToKotlinClass plugin via IntelliJ which comes close, but it does not seem to interpret required / optional directives correctly. E.g. given a schema with two properties, one required and the other optional -
    {
      "$schema": "<http://json-schema.org/draft-07/schema#>",
      "$id": "<https://abc.com/request.schema.json>",
      "title": "Request record",
      "type": "object",
      "properties": {
        "id": {
          "description": "The unique ID of a request",
          "type": "string"
        },
        "name": {
          "description": "The name of a request",
          "type": "string"
        }
      },
      "required": [
        "id"
      ]
    }
    I would expect to receive output like -
    data class Request(
        val id: String,
        val name: String?
    )
    but instead, this is generated (both fields are marked as required) -
    data class Request(
        val id: String,
        val name: String
    )
    Ideally I'd like to find a solution that can be implemented programatically too, rather than requiring a manual plugin (though that's not as important as getting the nullable part right).
    e
    m
    s
    • 4
    • 14
  • a

    Alexandre Marcondes

    06/29/2020, 5:29 PM
    Is there any Protobuf libraries that create kotlin data classes directly from the .proto files?
    d
    • 2
    • 9
  • a

    akshay

    06/30/2020, 3:57 PM
    https://proandroiddev.com/protobuf-in-android-55b01d855c40
    s
    • 2
    • 3
  • j

    Joe Masilotti

    07/01/2020, 6:24 PM
    Hey everyone! Long time iOS developer here looking to build my first Android app. Are there any tutorials or lessons you can recommend to get my feet wet? I'm looking to recreate an app I built with SwiftUI. Thanks and nice to meet everyone!
    a
    • 2
    • 2
  • l

    li-s

    07/03/2020, 4:32 AM
    Hey, could anyone help me with something? with the data class below:
    data class Item(val completed: Boolean, val details: String? = null)
    and a list:
    val p = listOf(
            Item(true, "one"),
            Item(false, "two"),
            Item(true, "three")
    	)
    I need to transform this data (truncate the second value in the Item to return something like:
    listOf(
            Item(true, "o"),
            Item(false, "t"),
            Item(true, "t")
    	)
    Im trying:
    val p = listOf(
            Item(true, "one"),
            Item(false, "two"),
            Item(true, "three")
    	)
        
        println(p.map { (_,details) -> details?.take(1) })
    but it returns: [o, t, t] What’s the best way to do this in Kotlin? Thank you in advance
    a
    m
    • 3
    • 5
  • h

    huehnerlady

    07/03/2020, 3:54 PM
    HI, I am quite new to kotlin. I have currently an generated Java interface containing spring Requestmapping annotations and extend this in my kotlin project. This works fine and the annotations are picked up and processed. When I generate the same interface as a kotlin interface though, these annotations seem to be ignored. Do I have to configure something to make this work?
    ✔️ 1
    m
    • 2
    • 19
  • t

    Tony Blundell

    07/04/2020, 12:20 AM
    Hi, What's the best way to abstract out the fromJson functionality so that it can be re-used? There doesn't seem to be a way to do it using interfaces that I can find...
    data class MyClass(val type: String) {
        companion object {
            fun fromJson(j: String) = Gson().fromJson(j, MyClass::class.java)
        }
    }
    
    data class MyOtherClass(val type: String) {
        companion object {
            fun fromJson(j: String) = Gson().fromJson(j, MyOtherClass::class.java)
        }
    }
    m
    • 2
    • 2
  • f

    Fedor

    07/04/2020, 12:06 PM
    Hi! I wonder why List<T>, where T is @Serializable is not @Serializable itself? There's a
    T.serializer().list
    serializer, that does exactly what I expect from List<T>.serializer(), but with this approach it seems like I have to write a custom serializer for any class that contains List in it
    i
    • 2
    • 2
  • n

    Nishoobansal

    07/04/2020, 2:47 PM
    can someone explain me enum classes. I didn't get what are they and it's my first time using enum classes
    n
    m
    r
    • 4
    • 3
  • d

    Dan O'Brien

    07/05/2020, 3:55 PM
    👋 I’m trying to understand what this error message is meaning:
    ERROR - pplication.impl.LaterInvocator - loader constraint violation: when resolving method 'com.intellij.ui.layout.CellBuilder com.intellij.ui.layout.Row.intTextField(kotlin.reflect.KMutableProperty0, java.lang.Integer, kotlin.ranges.IntRange)' the class loader com.intellij.ide.plugins.cl.PluginClassLoader @6ad38805 of the current class, com/github/intheclouddan/intellijpluginld/LaunchDarklyConfigurable$createPanel$$inlined$panel$lambda$4, and the class loader com.intellij.util.lang.UrlClassLoader @215be6bb for the method's defining class, com/intellij/ui/layout/Cell, have different Class objects for the type kotlin/ranges/IntRange used in the signature (com.github.intheclouddan.intellijpluginld.LaunchDarklyConfigurable$createPanel$$inlined$panel$lambda$4 is in unnamed module of loader com.intellij.ide.plugins.cl.PluginClassLoader @6ad38805, parent loader 'bootstrap'; com.intellij.ui.layout.Cell is in unnamed module of loader com.intellij.util.lang.UrlClassLoader @215be6bb, parent loader 'platform')
    I’m trying to use an intellij
    intTextField
    and just assign a var as
    refreshRate: Int
    n
    a
    • 3
    • 4
  • h

    Hannan Shaikh

    07/06/2020, 2:18 PM
    I have Android Interview day after tomorrow, so how should I prepare for that?
    :google: 3
    t
    h
    w
    • 4
    • 3
  • m

    Mark

    07/07/2020, 5:52 AM
    I have an extension function declared within a
    Fragment
    subclass:
    inline fun <T> Flow<T>.collectInViewScope(crossinline action: suspend (value: T) -> Unit) {
        viewLifecycleOwner.lifecycleScope.launch { 
            collect(action)
        }
    }
    But is there a way to declare this outside of the class (so it can be used from any
    Fragment
    subclass, without having to pass in the
    Fragment
    instance as an arg? A kind of extension function with added context of the call site. One could imagine
    inline <http://Fragment.fun|Fragment.fun> <T> Flow<T>.collectInViewScope(…)
    🇳🇴 2
    m
    • 2
    • 1
  • s

    Sam Smallman

    07/07/2020, 2:13 PM
    How would i translate 2 bytes from and to a UShort... I'm sure I'm missing something but functions dealing with Unsigned Integers and multiple bytes seems to be lacking from the standard library.
    s
    k
    • 3
    • 18
  • g

    Gus

    07/07/2020, 4:21 PM
    Hi. I'm writing a parser for a format that contains heterogeneous values that don't share a common class (other than
    Object
    ). What's the best / most idiomatic way to represent that collection? In TypeScript I'd do something like
    Array<Type1 | Type2>
    , but I don't know how to do something like that on Kotlin/Java/JVM.
    w
    • 2
    • 3
  • m

    Mark

    07/08/2020, 5:13 AM
    Is there any way to access a property delegate via an extension property? For example:
    class Settings(val sharedPreferences: SharedPreferences) {
        val appVersion: Int by <http://sharedPreferences.int|sharedPreferences.int>(APP_VERSION)
    }
    but I would like to do:
    val Settings.appVersion: Int by <http://sharedPreferences.int|sharedPreferences.int>(APP_VERSION)
    v
    a
    t
    • 4
    • 9
  • c

    Cheolho Jeon

    07/08/2020, 8:50 AM
    Been using Kotlin for 3, 4 yrs now. I recently took “Kotlin for Java Developers” on Coursera, and it was very interesting and there were a lot to learn. Wonder if there are more courses like this. I’m looking for a course for more experienced user, because the Coursera course took me 2 days to complete it. (and although I learned a lot there were lots of things I already knew.) Or a book like effective java of java. Any recommendations are welcome! Thanks.
    m
    • 2
    • 2
  • h

    horse_badorties

    07/09/2020, 6:37 AM
    Hi there, is Kotlin in Action still up-to-date? I had done some Kotlin 3 years ago. I would like to to refresh my memory now. Has anything of importance changed in Kotlin or was added to the language since then which is not covered in Kotlin in Action. Coroutines come to mind. Are there any other gotchas? Like major stdlib changes/additions?   Thanks!
    m
    h
    • 3
    • 2
Powered by Linen
Title
h

horse_badorties

07/09/2020, 6:37 AM
Hi there, is Kotlin in Action still up-to-date? I had done some Kotlin 3 years ago. I would like to to refresh my memory now. Has anything of importance changed in Kotlin or was added to the language since then which is not covered in Kotlin in Action. Coroutines come to mind. Are there any other gotchas? Like major stdlib changes/additions?   Thanks!
m

Matteo Mirk

07/09/2020, 8:53 AM
Hi, “Kotlin in Action” is a little bit dated on language and stdlib features but nonetheless still a great book, worth reading. For a list of updated books look here: https://kotlinlang.org/docs/books.html
h

Haomin

07/09/2020, 5:32 PM
Yes, agree with what Matteo has said. Still recommend the book. It is a very good read.
View count: 2