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

    myanmarking

    02/03/2020, 3:52 PM
    it says i cannot use it as a return type
    s
    m
    +2
    • 5
    • 8
  • m

    Mohammed Suleman

    02/03/2020, 3:57 PM
    Hello Can anyone Suggest me good Android book which i can use it from scratch.
    s
    • 2
    • 1
  • v

    vpriscan

    02/03/2020, 5:17 PM
    Can DeprecationLevel of @Deprecated method in a library depend on caller's Kotlin version?
    i
    • 2
    • 1
  • e

    Eyad Sibai

    02/03/2020, 6:03 PM
    Hi. Is it possible to call scala code from kotlin?
    :yes: 1
    ⚠️ 1
    b
    n
    c
    • 4
    • 3
  • b

    baxter

    02/03/2020, 7:50 PM
    When writing a file that is just extension functions, do you make the file uppercase or lowercase for the first letter? The context would be both in a pure Kotlin project, and a mixed project (Kotlin with Java interops).
    s
    • 2
    • 1
  • p

    Pablo Schmid

    02/03/2020, 9:20 PM
    Hi, is it possible to override a set and get function of a data class constructor var field? for example: data class Person(var name: String) I want to do something like fun setName(value: String){ this.name = value doSomethingElse() }
    n
    • 2
    • 2
  • v

    viralshah

    02/04/2020, 12:01 AM
    Hi Guys, is there a beginner’s guide to understanding coroutines and coroutine context/scope. I’m still kind of confused by how to create them. For frame of reference, I come from a CompletableFuture/ nodeJS Promise background
    :google: 4
    t
    r
    +2
    • 5
    • 5
  • j

    Jiri Bruchanov

    02/04/2020, 10:17 AM
    Kt public property is private in java Anyone who could help ?
    m
    d
    • 3
    • 6
  • a

    Awildrid

    02/04/2020, 3:14 PM
    Hello, I'm new to Kotlin but Java was the first language I learned back in 2010. I was wondering is there any binding for the python interpreter for Kotlin? I'm trying to develop an AI but also want to turn this into an app so that's why I wanted to go for Kotlin for the majority of the development and only develop the AI in python since there exists very nice deep learning frameworks. I tried searching for bindings to Kotlin for python and couldn't find anything... Basically what I'm hoping to find is something like this but for Kotlin: https://cppyy.readthedocs.io/en/latest/ I only need calling Kotlin from Python
    c
    c
    d
    • 4
    • 5
  • a

    APXEOLOG

    02/04/2020, 4:29 PM
    Example in docs throws an error. Not sure if intended or not
    a
    • 2
    • 1
  • g

    gbaldeck

    02/04/2020, 7:37 PM
    if I enable the spring compiler plugin in gradle, do I also need to enable the all-open plugin if I want to add additional annotations to the all-open list?
    c
    • 2
    • 1
  • t

    Thierry

    02/04/2020, 10:48 PM
    hi is there a jetpack compose specific channel?
    v
    • 2
    • 1
  • t

    Travis Griggs

    02/05/2020, 12:14 AM
    I have a simple "Observable" wrapper that I was playing with.
    class Slot<T> {
       private var _value:T
       var value:T
          get() = this._value
          set(newValue) {
             this._value = newValue
             // trigger notifications here
          }
    I wanted to add a variant of the
    value
    interface for types of
    T
    that are
    Comparable
    that would filter out no op changes. So I added the following extension:
    var <T : Comparable<T>>Slot<T>.concisely:T
       get() = this.value
       set(newValue) {
          if (this.value != newValue) {
             this.value = newValue
          }
    }
    This works like a charm...
    Slot<Int>(42).concisely = 42
    does just what I want. The inner
    value
    doesn't get called. Where this falls apart is when I have a
    T
    that is an optional.
    Slot<String?>("foo").concisely = "foo"
    won't even compile:
    Type for parameter bound T in
    var <T : Comparable<T>>Slot<T>.concisely:T
    is not satisfied: inferred String? is not a subtype of Comparable<String?>
    I have thrown various alternate incantations at my extension to try and accomodate optionals, but nothing seems to work. Is it even doable? What am I missing? I know that I can use
    ==
    on optional types...
    n
    m
    • 3
    • 8
  • a

    Aaron Stacy

    02/05/2020, 1:35 AM
    Is there any way to check if a Kotlin type is immutable at compile time (i.e. with some API in
    org.jetbrains.kotlin.types
    or
    <http://org.jetbrains.kotlin.ir|org.jetbrains.kotlin.ir>
    ?
    j
    • 2
    • 7
  • s

    steenooo

    02/05/2020, 8:36 AM
    Do typealiases persist after compilation?
    s
    k
    • 3
    • 4
  • t

    Timur Atakishiev

    02/05/2020, 9:20 AM
    Is it queue realization in kotlin?
    m
    • 2
    • 4
  • k

    Kroppeb

    02/05/2020, 10:39 AM
    Is it possible to make an extention-function that is only callable in the context off a certain type with certain type parameters?
    Untitled
    o
    s
    • 3
    • 3
  • k

    Kroppeb

    02/05/2020, 11:05 AM
    Both invocations are marked as ambiguous, which I find very weird.
    Untitled
    k
    m
    +2
    • 5
    • 11
  • g

    Gurupad Mamadapur [FH]

    02/05/2020, 12:19 PM
    Can someone please tell why the type R below is being erased even though it is reified?
    class BaseResponse<T> {
        val data: T? = null
        var someMessage: String? = null
    }
    
    class User {
        val name: String? = null
    }
    
    fun main() {
        val name = getUser<User>().data?.name
        println(name)
    }
    
    inline fun <reified R> getUser(): BaseResponse<R> {
    
        return if (testMessage == null) {
            BaseResponse<R>().apply { someMessage = "Some error" }
        } else {
            Gson().fromJson(
                testMessage,
                object : TypeToken<BaseResponse<R>>() {}.type
            )
        }
    }
    
    val testMessage: String? = """{"data": {"name":"Adam"},"someMessage":""}"""
    Error -
    Exception in thread "main" java.lang.ClassCastException: class com.google.gson.internal.LinkedTreeMap cannot be cast to class User (com.google.gson.internal.LinkedTreeMap and User are in unnamed module of loader 'app')
    	at MainKt.main(main.kt:54)
    	at MainKt.main(main.kt)
    If I send BaseResponse<User> as R instead of just User and return R, it works fine. But I want to return BaseReponse<R>.
    s
    • 2
    • 2
  • k

    Kris Wong

    02/05/2020, 3:10 PM
    when an anonymous object captures a
    var
    reference from the adjacent scope in one of its methods, does it not see changes to the original reference (i.e., it captures its own reference to the value when the object is created)?
    d
    • 2
    • 5
  • k

    kyleg

    02/05/2020, 4:03 PM
    I do DI into my fragments like so:
    class MyFragment : ... {
      @Inject lateinit var mViewModelFactory: ViewModelProvider.Factory
      private val mViewModel by lazy { 
        ViewModelProviders
          .of(requireActivity(), mViewModelFactory)
          .get(MyViewModel::class.java) // MyViewModel extends ViewModel
      }
    }
    Any idea how I might parametrize this into a base class to ideally get rid of ALL this boilerplate? I have
    abstract class BaseFragment<VM: ViewModel>: ... {
      abstract var mViewModelFactory: ViewModelProvider.Factory
      private val mViewModel by lazy {
        ViewModelProviders
          .of(requireActivity(), mViewModelFactory)
          .get(?????)
      }
    }
    This wuold at least enable
    class MyFragment<MyViewModel> {
      @Inject lateinit var mViewModelFactory: ViewModelProvider.Factory
    }
    But I’m stuck here. I thought about making a lookup table to map fragment classes to viewmodel classes, but would like to avoid that if possible. Thoughts? I doubt it can be done, but thought I’d ask here.
    k
    • 2
    • 2
  • m

    Mikołaj Karwowski

    02/05/2020, 4:05 PM
    Is that behavior intended? I don't understand why my val fields are null here o.O It's a data class inside a data class
    i
    • 2
    • 10
  • k

    kenkyee

    02/05/2020, 4:57 PM
    I'm trying to break up a large class by using class delegates (to avoid suppressing Detekt's TooLargeClass error), but finding it's not possible to access variables in the container class. How do folks handle something like this? class ContainerClass : X by ClassDelegate() { val something } class ClassDelegate { fun blah { // want to use something here... } }
    g
    • 2
    • 3
  • s

    Shan

    02/05/2020, 9:20 PM
    Is there a way to add an annotation to a class defined in a separate library? Some kind of extension annotation? E.g. I have a class called
    data class Foo()
    in my network library, but I would like to add an annotation to it in my Android
    app
    module for use with my database.
    g
    b
    • 3
    • 6
  • t

    Travis Griggs

    02/05/2020, 10:45 PM
    What is the idiomatic Kotlin way to translate the following Swift snippet:
    if let foo = someOptionalExpression, let bar = optionalExpression(foo) {
    // work with foo AND bar
    }
    else {
    // deal with nil/null case
    }
    z
    t
    +2
    • 5
    • 21
  • c

    Czar

    02/06/2020, 11:27 AM
    There is a lib which provides following API:
    suspend inline fun <reified T : Event> Client.addHandler(noinline action: suspend (T) -> Unit)
    I have a handler interface
    interface EventHandler<T : Event> {
        suspend fun handle(event: T)
    }
    And I have a list of handlers which is injected into my application:
    val handlers: List<EventHandler<*>>
    Each handler is defined as
    MyHandler : EventHandler<MyEvent>
    I need to somehow add these handlers to the client:
    handlers.forEach { client.addHandler(it::handle) }
    I'm getting
    Cannot use 'Nothing' as reified type parameter
    at the
    .addHandler
    What can I do to work around it?
    d
    • 2
    • 5
  • s

    Sam Garfinkel

    02/06/2020, 4:50 PM
    Is there anyway to get the KClass that corresponds to a given functional type? Because Kotlin doesn’t do SAM conversion for Interfaces, I’m kinda unsure how to pass a functional type to another function that accepts a KClass. I’m primarily interested in using this to bind a singleton to a function type for the purposes of injection.
    z
    d
    • 3
    • 38
  • g

    gbaldeck

    02/06/2020, 6:32 PM
    Something that has been bugging me for a while. What is the reasoning behind not allowing
    latinit val
    in Kotlin?
    s
    m
    d
    • 4
    • 37
  • j

    Jason

    02/07/2020, 4:36 AM
    Hi guys ! What is the main purpose of
    local function
    in Kotlin? ( As far as I know, it is used for reuse common code inside a function )
    f
    c
    m
    • 4
    • 5
  • z

    zjuhasz

    02/07/2020, 5:10 AM
    Does anyone know how to get IntelliJ to recognize a DSL and change the syntax highlighting for it. Only example of this I can find is ktor routing. Ktor routing builder functions do not show as the regular funciton color and I’m wondering how they accomplish this.
    s
    k
    • 3
    • 7
Powered by Linen
Title
z

zjuhasz

02/07/2020, 5:10 AM
Does anyone know how to get IntelliJ to recognize a DSL and change the syntax highlighting for it. Only example of this I can find is ktor routing. Ktor routing builder functions do not show as the regular funciton color and I’m wondering how they accomplish this.
I mean when creating a new DSL not trying to get it to recognize any DSL and change the highlighting.
s

serebit

02/07/2020, 5:26 AM
Use the
DslMarker
annotation
z

zjuhasz

02/07/2020, 5:28 AM
I’ve been using that, it doesn’t seem to effect syntax highlighting. Just avoids issues with nested receivers.
Maybe I’m using it wrong
Yeah I was annotating the receiver type instead of the function itself
How does it decide which “Dsl style” to use? There are 4 in IntelliJ settings.
k

Kroppeb

02/10/2020, 11:21 PM
It uses a hash to determine which style to use. If you want to make sure 2 markers have a different color, you gotta try some names until you get the one you like.
View count: 4