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

    Vitali Plagov

    04/23/2020, 1:05 PM
    I have the following regex in JS -
    /[()\/]/g
    that matches
    (
    ,
    )
    ,
    /
    anywhere in a string. Why exactly the same pattern doesn’t work with Kotlin when I pass it to the
    Regex
    ?
    d
    k
    +1
    12 replies · 4 participants
  • a

    Animesh Sahu

    04/23/2020, 2:11 PM
    Could somebody help me in https://stackoverflow.com/q/61389146/11377112. In short i have a dependency which specifies kotlin plugin as:
    id 'org.jetbrains.kotlin.jvm' version 1.+
    and it fetches 1.4-M1, and that version of kotlin-stdlib-jdk8 dependency is not available, it errors:
    Could not find org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.4-M1.
    
    Possible solution:
     - Declare repository providing the artifact, see the documentation at <https://docs.gradle.org/current/userguide/declaring_repositories.html>
    a
    i
    3 replies · 3 participants
  • j

    Justin Breitfeller

    04/23/2020, 4:12 PM
    Hello I have an interface like the following. For some reason, if I try to pass a method reference like
    MyJavaClass::hasData
    as an
    IsStateRunningCheck
    argument I get the following error. Found KFunction1 and not my interface. Is this an instance of SAM conversion not working properly or is there something I can do to make this possible.
    @FunctionalInterface
    protected interface IsStateRunningCheck<T> {
        boolean isStateRunning(T state);
    }
    For instance:
    fun myFooMethod(stateCheck: IsStateRunnningCheck<Int>) { ... }
    
    fun test() {
       myFooMethod(MyJavaClass::hasData) // fails to compile
       myFooMyethod( { it.hasData() }) // works fine
    }
    
    // I don't think it matters if this is java or not
    class MyJavaClass<Int> { 
      boolean hasData(int x) { return true; }
    }
    e
    3 replies · 2 participants
  • a

    Animesh Sahu

    04/23/2020, 4:22 PM
    How do i unescape an html string to render it perfectly in browser? I am using https://github.com/lukasjapan/koreander library! Here is extended information of code and output: https://stackoverflow.com/questions/61391828/how-to-unescape-html-in-string-in-koreander-templates
    d
    4 replies · 2 participants
  • l

    Luis Munoz

    04/23/2020, 5:20 PM
    Is there a functional style of doing a do while (so that I don't have to create a variable before entering loop)? Basically I have an array and I generate a new array with 1 less element, when no more elements or the array is in the desired state the loop is done.
    s
    j
    8 replies · 3 participants
  • s

    Slackbot

    04/23/2020, 10:07 PM
    This message was deleted.
    s
    4 replies · 2 participants
  • s

    Slackbot

    04/24/2020, 9:51 AM
    This message was deleted.
    m
    h
    +1
    3 replies · 4 participants
  • j

    Jiri Bruchanov

    04/24/2020, 1:20 PM
    invalid access to protected function, weird issue
    d
    8 replies · 2 participants
  • s

    Sam Garfinkel

    04/24/2020, 8:25 PM
    What’s the correct way to access the synthesized Java class for a non-class function? Need it for resource loading purposes.
    1 reply · 1 participant
  • a

    Ahmed Mourad

    04/25/2020, 1:58 AM
    Around when should we expect 1.4 to be stable?
    r
    a
    2 replies · 3 participants
  • c

    czyzby

    04/25/2020, 9:33 AM
    I have a question about Kotlin contracts. As a library creator, how can I define functions that leverage contracts without forcing the users to use
    OptIn
    annotation or compiler flags? Should I annotate my methods/files with
    @OptIn(ExperimentalContracts::class)
    ?
    a
    z
    +1
    8 replies · 4 participants
  • g

    Gopal S Akshintala

    04/25/2020, 1:49 PM
    Why DOESN’T Kotlin smart cast work here?
    fun SLLNode?.sumListWith(node: SLLNode?, carry: Int = 0): SLLNode? =
        when {
            this == null && node == null -> if (carry == 0) null else SLLNode(carry)
            this == null -> node.also { it!!.value += carry } // Smart cast doesn't work here.
            node == null -> this.also { value += carry } // Works here.
            else -> {
                ...
            }
        }
    v
    a
    6 replies · 3 participants
  • h

    hnOsmium0x0

    04/26/2020, 4:53 AM
    Can you use an elvis operator on a Pair's contents?
    a
    2 replies · 2 participants
  • s

    Slackbot

    04/26/2020, 8:21 AM
    This message was deleted.
    :android: 1
    k
    l
    +1
    3 replies · 4 participants
  • t

    Tim Malseed

    04/26/2020, 10:13 AM
    Does anyone here have experience with CMake? I’ve got what I think is a fairly simple problem - just struggling to find headers included via a library project
    z
    1 reply · 2 participants
  • j

    Joan Colmenero

    04/26/2020, 12:02 PM
    Have a question with Kotlin syntax but it's related about Retrofit, is this the correct place to do it? I'm about to create an inline function and use generics... Let me know if I can ask it here
    t
    z
    2 replies · 3 participants
  • s

    steenooo

    04/26/2020, 2:57 PM
    Am I doing something wrong? This lazy is the normal lazy from the kotlin stdlib
    g
    l
    2 replies · 3 participants
  • p

    pablisco

    04/26/2020, 5:41 PM
    I’m curious about how people use
    Map
    in Kotlin. What do y’all do? https://twitter.com/pablisc0/status/1254465101224120324
    d
    r
    +3
    19 replies · 6 participants
  • c

    Colton Idle

    04/26/2020, 6:14 PM
    Do most people stay away from using kotlin standard functions? I just joined a project where they advise to not use them as it adds overhead to having to think about what's actually going on. I understand that these functions are just another tool in your toolbelt, and so it's up to everyones discretion on whether or not we should use that tool, but does anyone have similar feelings about typically not using them? Converting 5 lines to 4 doesn't seem like an improvement most times. Is there a good reason to use any of them? I've read that functions like let and apply are probably the most useful so that you don't have to do
    myobject.somethingInner.somethingNested.setter1 = true
    myobject.somethingInner.somethingNested.setter2 = false
    myobject.somethingInner.somethingNested.setter3 = false
    That seems like a legitimate use case to me to not have to repeat so you can do
    myobject.somethingInner.somethingNested.apply {
    setter1 = true
    setter2 = false
    setter3 = false
    }
    I also read that this makes things thread safe. So while that sounds good. I don't know what that actually means. Is my first statement not thread safe?
    a
    d
    +3
    18 replies · 6 participants
  • p

    Peter Kucera

    04/27/2020, 1:18 PM
    Hi all, I am porting some Kotlin/JVM code to Kotlin/Native - original logic relied heavily on ByteBuffer, which was used for parsing Float / Double / Long etc.. values out of one long ByteArray. In Kotlin Native ByteBuffer is not available, is there some easy way to parse ByteArray contents? I am using Kotlin 1.3.71
    z
    4 replies · 2 participants
  • v

    Vincent Williams

    04/27/2020, 4:15 PM
    Hi, Im splitting my app into multiple modules and im having some trouble with enums. I have 3 modules (network, database, repository). They all have their own data entity classes that use enums for certain fields (for example verificationStatus in the server response would be an enum). Should I have separate enums in each layer or should I share one class between all 3? Right now im having the enums only in the repository layer but im not sure if thats the best way
    p
    b
    4 replies · 3 participants
  • k

    Krish

    04/27/2020, 5:10 PM
    Hey guys, is it possible to extend a data class with an abstract class? My use case is as follows, I have a CommonResponse Params abstract class
    abstract class CommonResponseParams (
        val type: String,
        val code: String,
        val message: String,
        @SerializedName("request_id")
        val requestId: String,
        val detail: CommonDetailsResponseObject?
    )
    And I have a more specific Response Params which has the Common Params on top of it I wish to extend this data class with the abstract class above
    data class GetCategoryAttributeResponse (
        val commonDetails : CommonDetailsResponseObject,
        @SerializedName("data")
        val getCategoryData: CategoryAttributeResponseData
    )
    d
    1 reply · 2 participants
  • k

    Krish

    04/27/2020, 5:12 PM
    Coming from a Typescript world, it would be something like
    interface Response extends CommonResponseParams {
     // API endpoint specific params
    }
    :thread-please: 1
    s
    k
    4 replies · 3 participants
  • u

    user

    04/28/2020, 9:30 AM
    message has been deleted
    😍 3
    🎉 1
    j
    d
    3 replies · 2 participants
  • a

    akshay_b

    04/28/2020, 1:27 PM
    Hello All, The code 
    object : GenericType<Pair<F, S>>() {}
    produces raw type of 
    GenericType<Pair<? extends F, ? extends S>>
     how to remove 
    ? extends
    Thanks in advance 🙂
    d
    2 replies · 2 participants
  • a

    Antoine Gagnon

    04/28/2020, 1:52 PM
    Hello all, Quick formatting question, when chaining calls with lambdas, which one is correct: (provided the code inside the brackets is longer than one line) 1.
    (1..10).filter {
        it < 5
    }
        .map {
            val double = it * 2
            double*3
        }
        .map {
            it.dec()
            it + 5
        }
    2.
    (1..10).filter {
        it < 5
    }.map {
        val double = it * 2
        double * 3
    }.map {
        it.dec()
        it + 5
    }
    The coding convention suggests that when chaining calls you should put each call on a new line starting with a dot but I don’t how if it applies to lambdas and other {} things
    2️⃣ 6
    1️⃣ 1
    d
    d
    +4
    14 replies · 7 participants
  • t

    Twferrell

    04/28/2020, 2:49 PM
    Hi all, very general Kotlin question here. Is there a way to access a property of a context object when using when clause? For example let's say I have someObj reference which has a string property of propOfSomeObj. when (someObj) { ::propOfSomeObj.isBlank() -> ... }
    🇳🇴 1
    r
    s
    5 replies · 3 participants
  • l

    LastExceed

    04/28/2020, 5:03 PM
    how do I properly implement
    .toSentence()
    ? the difficult part is not having leading or trailing whitespaces
    Untitled
    z
    2 replies · 2 participants
  • c

    Chung

    04/28/2020, 11:55 PM
    I have a function which returns an object of
    ViewHolder
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return when (viewType) {
            0 -> ViewHolder(CategoryHeaderBinding.inflate(LayoutInflater.from(parent.context), parent,false))
    
    
            else -> ViewHolder(CategoryCardBinding.inflate(LayoutInflater.from(parent.context), parent, false))
        }
    }
    it passes either
    CategoryHeaderBinding
    or
    CategoryCardBinding
    to
    ViewHolder
    class ViewHolder(private val binding: CategoryCardBinding OR CategoryHeaderBinding) :
            RecyclerView.ViewHolder(binding.root) {
        }
    How do I make
    ViewHolder
    accepts
    binding
    to be either
    CategoryCardBinding
    or
    CategoryHeaderBinding
    c
    r
    8 replies · 3 participants
  • t

    Thomas Nordmeyer

    04/29/2020, 6:41 AM
    Hi guys, is there a better way to express a delegated property
    var mapType
    get() = map.mapType
    set(value) {
    map.mapType = value
    }
    I know we have Delegates but can those be used in a more simple way than my implementation above?
    s
    a
    4 replies · 3 participants
Powered by Linen
Title
t

Thomas Nordmeyer

04/29/2020, 6:41 AM
Hi guys, is there a better way to express a delegated property
var mapType
get() = map.mapType
set(value) {
map.mapType = value
}
I know we have Delegates but can those be used in a more simple way than my implementation above?
s

Sam Garfinkel

04/29/2020, 6:45 AM
You’d have to implement the
setValue
and
getValue
operators for whatever type
map
is then you can use
var mapType by map
The delegate pattern where you implement the operators is really only useful if the type is delegated to a lot. For one-offs using the backing field directly like you have is perfectly fine.
t

Thomas Nordmeyer

04/29/2020, 7:24 AM
OK, thanks. Then I already have the shortes implementation . Thought there would be something like
var mapType by proxy(map.mapType)
or even
var mapType proxies map.mapType
somehow generic. Quiet common use case when encapsulating 3rd party components.
a

araqnid

04/29/2020, 8:45 AM
You can probably write something to do
var mapType by proxy(map::mapType)
if you’re using it a lot, and then write it up as a suggestion for stdlib
View count: 2