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

    F0X

    01/28/2021, 9:48 PM
    Is there an idiomatic Kotlin way of doing this (with
    T
    being a reified type paramter)?
    SomeClass::class.java.isAssignableFrom(T::class.java)
    n
    e
    • 3
    • 9
  • f

    F0X

    01/29/2021, 3:42 PM
    If I have a base class with an extension property like this
    open val SomeType.someProp: String
    , how could I call the super implementation of this when overriding it in a subclass?
    m
    j
    +2
    • 5
    • 9
  • d

    Daniele B

    01/29/2021, 5:25 PM
    I have a list of MyObj, already sorted by date:
    data class MyObj (
        val date : String,
        val dailyAmount : Int,
        val cumulativeAmount : Int,
    )
    where
    cumulativeAmount
    is empty I would like to iterate over that list, and populate
    cumulativeAmount
    with the sum of all
    dailyAmount
    until that date How to do?
    e
    n
    t
    • 4
    • 9
  • h

    Héctor Alpízar

    01/30/2021, 4:25 AM
    Hi, everybody, I'm working on a 3rd party library for KMM (Android, iOS). Any best practices you recommend me? Books, tutorial, advice?
    f
    • 2
    • 1
  • v

    Vinay Reddy

    01/30/2021, 10:23 AM
    Hello everyone! I'm new to Kotlin and am trying to write a dummy gRPC client/server in Kotlin to get started. The rest of my repository uses the bazel build system, so I was hoping to continue using it. Is this reasonable, or should I be switching to gradle for Kotlin? Assuming bazel works I see that there's https://github.com/grpc/grpc-kotlin to help generate files for my protos, but I don't see very many bazel examples of grpc-kotlin. I'm trying to figure out what to add to my WORKSPACE file (version, sha256 etc.). When I add this to my workspace and try to build my proto I see an error.
    rules_kotlin_version = "legacy-1.3.0"
    rules_kotlin_sha = "4fd769fb0db5d3c6240df8a9500515775101964eebdf85a3f9f0511130885fde"
    http_archive(
        name = "io_bazel_rules_kotlin",
        urls = ["<https://github.com/bazelbuild/rules_kotlin/archive/%s.zip>" % rules_kotlin_version],
        type = "zip",
        strip_prefix = "rules_kotlin-%s" % rules_kotlin_version,
        sha256 = rules_kotlin_sha,
    )
    
    load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kotlin_repositories", "kt_register_toolchains")
    kotlin_repositories()
    kt_register_toolchains()
    
    http_archive(
        name = "kt_jvm_grpc",
        sha256 = "ccf10e35ba2ff01f594b8fdd4f2ff2426bfd7ec2a676eace4c116e9d4794e49c",
        urls = ["<https://github.com/grpc/grpc-kotlin/archive/v1.0.0.tar.gz>"],
    )
    load("@kt_jvm_grpc//:repositories.bzl", "grpc_kt_repositories")
    grpc_kt_repositories()
    The error is:
    ERROR: error loading package '': Every .bzl file must have a corresponding package, but '@kt_jvm_grpc//:repositories.bzl' does not have one. Please create a BUILD file in the same or any parent directory. Note that this BUILD file does not need to do anything except exist.
    This is a public library that I'm simply including. Not sure what to do to fix this error. Would appreciate any help. Thanks!
    • 1
    • 1
  • o

    oday

    02/01/2021, 2:39 PM
    how can I translate this to Kotlin?
    class Solution(object):
      def _isValidBSTHelper(self, n, low, high):
        if not n:
          return True
        val = n.val
        if ((val > low and val < high) and
            self._isValidBSTHelper(n.left, low, n.val) and
            self._isValidBSTHelper(n.right, n.val, high)):
            return True
        return False
    
      def isValidBST(self, n):
        return self._isValidBSTHelper(n, float('-inf'), float('inf'))
    my attempt produced this
    fun isValidChecker(
        node: Node<Int>?, low: Int, high: Int
    ): Boolean {
        if (node == null)
            return true
    
        val value = node.value
    
        if (value in (low + 1) until high
            && isValidChecker(node.left, low, value)
            && isValidChecker(node.right, value, high)
        )
            return true
    
        return false
    }
    
    fun isValidBST(node: Node<Int>?): Boolean {
        return isValidChecker(
            node, Int.MIN_VALUE, Int.MAX_VALUE
        )
    }
    r
    • 2
    • 18
  • o

    oday

    02/01/2021, 8:08 PM
    why can’t I do this?
    val map = mutableMapOf<Char, Int>()
    
    map['a'] += 1
    r
    h
    n
    • 4
    • 29
  • s

    Sachin Rana

    02/02/2021, 2:10 PM
    #getting-started Hi All, Does anyone tell me the difference between Kotlin data types and Java data types? As, I am learning about Kotlin data types and I found that in case of Kotlin Data Type we can directly use method like minus, divide etc. directly without using Wrapper Classes as we use in case of Java.
    n
    • 2
    • 3
  • s

    Slackbot

    02/02/2021, 11:26 PM
    This message was deleted.
    n
    r
    • 3
    • 24
  • s

    Stefán Freyr Stefánsson

    02/03/2021, 11:07 AM
    Hello, I have a basic question about file streams. I want to concatenate multiple files into one. I see that the File object has
    appendText
    and
    appendBytes
    but what do I do if I want to append an input stream? There’s
    copyTo
    but that replaces the whole file and I don’t want to read the whole input stream into a byte array (for
    appendBytes
    ) because of memory usage. Will I have to handle the buffering myself and write a decorator function (
    File.appendStream(inputStream: InputStream)
    ) or does something else exist?
    m
    v
    n
    • 4
    • 31
  • s

    supra

    02/04/2021, 7:50 AM
    private fun transformDepsRecursively(target: Project, from: Map<*, *>, to: MutableMap<*, *>) {
        log.quiet("$TAG transformDepsRecursion start")
        from.forEach {
            val valueFrom = it.value
            var valueTo = valueFrom;
            if (valueFrom is ProjectDescriptor) {
                valueTo = target.project(valueFrom.path)
            } else if (valueFrom is Map<*, *>) {
                valueTo = mutableMapOf<String, Any>()
                transformDepsRecursively(target, valueFrom, valueTo)
            }
            mapOf<Any,Any>()
            to[it.key]=valueTo
        }
        log.quiet("$TAG transformDepsRecursion end")
    }
    a
    • 2
    • 4
  • o

    oday

    02/04/2021, 4:33 PM
    does Kotlin work only for JVM?
    🇳🇴 8
    r
    m
    • 3
    • 3
  • a

    Allen Eubank

    02/04/2021, 5:28 PM
    Hello, I’m sort of stuck or I’m not sure how to search for answer to this question, but I’m writing an interface and abstract class that works with a generic type. The implementation works with SQS and uses kotlinx.serialization to de/serialize messages to JSON. But the serialization library is causing this compiler error,
    Cannot use 'T' as reified type parameter. Use a class instead.
    . Is there a way to keep `sendMessage/receiveMessage`` in the abstract class? Or do I have to move it into the concrete implementation?
    i
    • 2
    • 2
  • p

    poohbar

    02/04/2021, 6:31 PM
    "UMSR65US5BUFE7PS5SNWWKTWU=====".removeSuffix("=")
    evaluates to
    UMSR65US5BUFE7PS5SNWWKTWU====
    what am i missing?
    a
    • 2
    • 2
  • m

    Muhammed khaled

    02/08/2021, 5:38 AM
    Hey guys, i've a project and want to bulid it as kotlin multiplatform "Android, ios, Web" appliction where i can start kmm or from where please send me any guide or doc to start with it
    o
    m
    • 3
    • 2
  • a

    acoconut

    02/08/2021, 2:58 PM
    I know I can assign a the result of an if statement to a variable, but is there any difference between if with {} and if with () ?
    a
    m
    +2
    • 5
    • 18
  • s

    Slackbot

    02/08/2021, 11:24 PM
    This message was deleted.
    v
    r
    • 3
    • 2
  • v

    vineethraj49

    02/09/2021, 11:12 AM
    do we have some documentation for this behavior?
    val foo: String
    // foo cannot be used yet
    if (cond) {
      ...
      foo = "a"
      ...
      foo can be used here
    } else {
      ...
      foo = "b"
      ...
      foo can be used here
    }
    
    // foo can be used now
    v
    • 2
    • 1
  • o

    Omar Ayadi

    02/11/2021, 2:46 PM
    hello guys, i have written this medium article, it was published by the start up, can i get your reviews please? https://medium.com/swlh/10-advanced-kotlin-tricks-6e773306b6b8
    r
    h
    o
    • 4
    • 5
  • o

    oday

    02/12/2021, 11:29 AM
    can I turn the keys of a Map<String, Int> into a String array?
    y
    • 2
    • 3
  • n

    Nat Strangerweather

    02/13/2021, 4:25 PM
    Hi, I'm a bit confused as I have been using an
    AndroidViewModel
    so I could pass a context with no memory leak, after this conversation: https://kotlinlang.slack.com/archives/C0B8MA7FA/p1609278349460800?thread_ts=1609277107.460700&amp;cid=C0B8MA7FA The problem since I've recently updated Kotlin is that this line is highlighted with a leak warning:
    private val context = getApplication<Application>().applicationContext
    Why this change and what's the point of
    AndroidViewModel
    in that case? Any ideas what I could do to avoid the problem?
    i
    l
    • 3
    • 4
  • i

    iona bartishvili

    02/14/2021, 6:49 PM
    Hi ! Can i ask a question about Ktor ? On wich channel ? Or does someone has a little experience who may help me with very fundamental problem ?
    n
    • 2
    • 4
  • r

    Roger Gilliar

    02/14/2021, 7:47 PM
    Hi. I currently have an existing ktor project that I wan't to split in one main project and 3 modules. I tried to add source sets to the gradle build and tried to follow different tutorials from around the web but none worked for me. What I primarily want is to have different Kotlin modules that only publish their public API's and that those public API's can be consumed by the main program. Something like a maven setup that supports Java modules.
    j
    • 2
    • 1
  • k

    Ky

    02/15/2021, 2:53 AM
    Hey guys, I’m coming from RxJava world and having some trouble implementing a debounce operator on a Jetpack compose TextField using
    Flow
    . So this works as expected
    CoroutineScope(IO).launch {
                flow<Int>{
                    emit(1)
                    delay(350)
                    emit(2)
                    delay(100)
                    emit(3)
                }.debounce(300)
                    .collect {
                        Timber.d(it.toString())
                    }
            }
    
    Output: 1, 3
    However trying to apply this same idea to a searchview I have..
    TextField(
                        modifier = Modifier
                            .fillMaxSize()
                            .background(
                                color = MaterialTheme.colors
                                    .elevatedSurface(3.dp)
                                    .copy(alpha = 0.95f)
                            ),
                        value = searchTerm.value, onValueChange = { newValue ->
                            searchTerm.value = newValue
                            CoroutineScope(IO).launch {
                                queryFlow(newValue.text, viewModel)
                            }
                        })
    This is
    queryFlow
    suspend fun queryFlow(query: String, viewModel: TwitMainViewModel) = flow {
        Timber.d("Emitting: ${query}")
        emit(query)
        delay(500)
    }.debounce(1000)
        .filterNot {
            it.isEmpty()
        }
        .collect {
            Timber.d("MAKING REQUEST FOR: $it")
            viewModel.search(it)
        }
    So in this case, even if I rapid type
    nnn
    a request is made for each; being
    n
    nn
    and
    nnn
    . The debounce operator has no effect here. I can’t identify why however, any ideas? Thanks
    a
    a
    • 3
    • 6
  • l

    Lewis Diamond

    02/15/2021, 4:07 AM
    Is there a built-in way to read stdin as a stream? Something like Node's
    process.stdin
    ?
    n
    • 2
    • 6
  • t

    Tianyu Zhan

    02/15/2021, 4:27 PM
    How should I run gradle-client app in examples? I have errors when I run
    gradle clean build
    v
    • 2
    • 1
  • d

    Dave Trollope

    02/15/2021, 9:34 PM
    Hey folks, I started my Kotlin journey over christmas, and decided this month to rewrite a RubyMotion based app I have in Kotlin and support both iOS and Android which I never succeeded with in RM. So after researching, I dived in to KMM, (realizing its still in alpha state) and have really struggled to get started. Following the https://kotlinlang.org/docs/mobile/getting-started.html page left me with more questions than answers. Part of my challenge was, which IDE to use from the outset (I have a jetbrains toolbox license) and got the impression I should start with IntelliJ and the KMM plugin. After struggling to get https://github.com/Kotlin/kmm-sample doing anything, I realized that Android Studio seems to be the place to start. Switching to that I got Android working very quickly, but fell foul of the known issue where the iosApp doesn't appear in the Run Configuration. It still seems unclear to me if I should be relying on Xcode for iOS and AS for Android, or wait for the fixes to the iOS run config related issues (it is alpha after all). For now, I'm switching to Kotlin Native for iOS with a plan to port back in to KMM when its more stable. So I have 2 questions: 1. Where is the appropriate forum to get feedback to the maintainers of the KMM getting started guide? Maybe even contribute if I can, as I learn. 2. When I get a native iOS app built, am I setting myself up for a big challenge switching to KMM to build a single app that supports Android too?
    m
    b
    • 3
    • 8
  • v

    vineethraj49

    02/17/2021, 1:39 PM
    inb4 please don't lynch me please give me pointers on how .copy works when data class overrides an abstract class
    n
    c
    • 3
    • 4
  • p

    poohbar

    02/17/2021, 3:43 PM
    If I have a variable:
    val block: () -> Any? = ...
    is there a difference between calling:
    block()
    and
    block.invoke()
    ?
    🇳🇴 2
    m
    l
    e
    • 4
    • 4
  • s

    speed_star

    02/18/2021, 3:44 PM
    Hi. I'd like to define
    Entity
    for domain of DDD in Kotlin. Is my field definition correct? I use
    val
    for
    id
    because this field is immutable. And I use
    var
    for
    name
    and
    status
    because they are mutable fields. All fields are
    private
    to prevent to be updated directly from the outside.
    Untitled
    c
    m
    +2
    • 5
    • 8
Powered by Linen
Title
s

speed_star

02/18/2021, 3:44 PM
Hi. I'd like to define
Entity
for domain of DDD in Kotlin. Is my field definition correct? I use
val
for
id
because this field is immutable. And I use
var
for
name
and
status
because they are mutable fields. All fields are
private
to prevent to be updated directly from the outside.
Untitled
c

CLOVIS

02/18/2021, 4:07 PM
You could probably use an
enum
for the status instead of a
String
.
s

speed_star

02/18/2021, 4:13 PM
I see. thank you.
m

Moritz Mücke

02/18/2021, 4:13 PM
you could also use a data class i guess
s

speed_star

02/18/2021, 4:17 PM
In my understand data class is used for
value object
. Because data class is the same as the
value object
because it is considered the same object if all the fields are the same. Data class can also be used for
Entity
?
n

nanodeath

02/18/2021, 4:57 PM
OT: you guys are like a stoplight 😛
➕ 1
🤣 5
c

CLOVIS

02/18/2021, 5:16 PM
@speed_star
value class
is a future syntax,
data class
just means “please generate
toString
,
hashCode
and a few other convenient things (
copy
,
componentN
...)”. You can still
override
those you don't like.
👍 1
s

speed_star

02/18/2021, 5:36 PM
I got it :)
k

kqr

02/18/2021, 6:07 PM
but with vals and @NoCopy you basically get valueobject 🙂
View count: 12