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

    Ayfri

    11/25/2022, 9:06 PM
    Hi ! Is there any reliable way to create a zip from a folder ? I've seen 5 pages from StackOverflow and tried all the examples listed and I still come up with a zip that doesn't work with Minecraft because Minecraft is extremely strict with Zip files :/
    j
    p
    a
    • 4
    • 28
  • v

    Vishal Rao

    11/26/2022, 9:23 AM
    list[2:5] = mlist
    This python code assigns mlist into list at indices 2 to 5. I am not able to do the same in kotlin using inbuilt methods. Can anyone help me.
    s
    e
    r
    • 4
    • 8
  • t

    Tech

    11/26/2022, 4:10 PM
    Hey I was wondering if it was possible to use settings in the root gradle.properties in my sub-projects? I tried accessing like this
    val test: String by rootProject
    but that just produces null. Thank you in advance.
    v
    • 2
    • 28
  • a

    Antonio Acuña Prieto

    11/27/2022, 1:07 PM
    Any good gradle course? Updated if it’s possible to use with Kotlin. I plan to use Gradle to manage monorepos
  • a

    Aleksandr

    11/27/2022, 1:41 PM
    Hi! I’m new to Kotlin and compiled languages and my question is: are there some practice to develop server application? I want to add an ability to our team unwrap project with some microservices in a couple of clicks for development. So things I’m trying to do is setup docker compose with these service, DB, etc. mount code via volume to app container and run by command. It is good way to develop JVM application or not? I asked because a lot of examples made by just compiling jar, copy to container and run from it and examples like that. These examples seem not as good decisions, because we need to recompile it every time and build again and again and also because we can use auto-rebuild on code changes that we don’t use. So could anyone explain? Thanks!
    j
    h
    s
    • 4
    • 6
  • r

    Rohan Maity

    11/27/2022, 4:44 PM
    Which channel would be great to discuss the kotlin language itself? I am not getting any channel name general ?
    j
    • 2
    • 3
  • d

    Daniel Souza Bertoldi

    11/27/2022, 4:56 PM
    Hi! I’ve been following a tutorial on how to create a mini compiler, but the tutorial is in JavaScript. I’m trying to convert it to Kotlin, and I’ve ran into the following problem (detailed in the thread) and I’m not sure how to solve it.
    j
    • 2
    • 4
  • r

    Rodrigo Silva

    11/27/2022, 8:58 PM
    Hi all. I'm creating a class to encrypt and decrypt strings using bouncy castle. everything works perfect that way:
    k
    • 2
    • 7
  • h

    hfhbd

    11/28/2022, 11:37 AM
    What are the technical reasons for
    1.7.22
    ?
    a
    • 2
    • 1
  • u

    Ulises Serrano

    11/28/2022, 3:29 PM
    Hello everybody, I'm new in this slack, I'm from México and I feel so exited to learn and discovery new things all the days.
  • x

    xun su

    11/29/2022, 12:36 AM
    Hi, I'm new to serialization(in JS it is just about JSON.stringify and JSON.parse from my perspective) , could someone tell me why the code below doesn't print
    name:"foo"
    ? though I didn't initialize the field in the constructor, but they got a default value.
    d
    l
    • 3
    • 4
  • t

    Tracey Yoshima

    11/29/2022, 12:39 AM
    Hi everyone! I’m new to the Kotlin slack and would like to create an OpenRewrite AST for Kotlin. I want to use the Kotlin compiler to collect the type attribution of Kotlin and Java sources. The goal is primarily to have a Kotlin AST that will allow us to migrate APIs. I’m having trouble creating a
    FirSessionFactory.INSTANCE
    using
    createLibrarySession
    and am getting an error (will be linked in thread). Could someone point me to an example of how to instantiate the Kotlin compiler?
    d
    • 2
    • 6
  • a

    Android Mahi

    11/29/2022, 1:20 AM
    👋 Hello, team!
  • k

    Kroppeb

    11/29/2022, 4:49 PM
    Is there an easy/already existing way to replace all integer additions, subtractions and multiplications to strict math variants in kotlin code?
    j
    c
    +2
    • 5
    • 11
  • j

    Jakub Gwóźdź

    11/30/2022, 2:01 PM
    Hi there. I have a general question about generics. Suppose I have input data in form of lines, each matching some regex that could be then mapped to a data class or whatever. But on each day it will be different format, different regex and data. YES it’s #advent-of-code time again 🙂 I created an extension function to help me deal with it:
    fun <R> String.parseRecords(regex: Regex, op: (MatchResult) -> R): Sequence<R> =
        lineSequence().filterNot(String::isBlank)
            .map { regex.matchEntire(it) ?: error("WTF `$it`") }
            .map(op)
    That works just fine. How would it look like if I want to make parameters optional (with some default mapping)? I can use
    regex: Regex = "(.*)"
    but the
    op: (MatchResult) -> R = { it.destructured.component1().toInt()}
    is a big no-no, because of Type mismatch: inferred type is Int but R was expected. Is it even possible to add default parameter values for generic functions?
    s
    • 2
    • 2
  • i

    iGrid

    11/30/2022, 2:16 PM
    Non programmer I want to learn Kotlin to create Android apps and design them in a way that I can port them to iOS as well. Please share the best way to start learning. Any course would do.
    c
    m
    • 3
    • 14
  • c

    Craig

    11/30/2022, 4:31 PM
    Hey everyone, I'm looking for a solution to keep track of coroutines launched from a hot flow so I can cancel them if the same event arrives again. I've created this distilled example of combining a state flow but I'm not sure if this is safe/intended usage. Is updating state inside of the flow an anti-pattern?
    @Test
        fun start() {
            val sourceFlow = (0..20).asFlow()
            val stateFlow = MutableStateFlow(mutableMapOf<String, Int>())
    
            runBlocking {
                stateFlow.asStateFlow().combine(sourceFlow) { state, number ->
                    println("got number $number")
                    state[(number % 2).toString()] = number
                    state
                }
                    .take(20)
                    .collect { result -> println("got result $result") }
            }
        }
    s
    e
    • 3
    • 9
  • x

    xun su

    11/30/2022, 5:47 PM
    Hi, is there optional parameters in Kotlin ? the doc have no hints about that. I've marked the param
    info
    as
    nullable
    , why still got error?
    v
    r
    k
    • 4
    • 7
  • d

    Daniel Felipe Henao Toro

    11/30/2022, 7:22 PM
    Hi there, please someone can give me a few explanation about the use of text@ and @text after run function, please check the following code:
    private fun getClickTagName(textOptions: List<String>, tag: StringBuilder): String {
            var textToSearch = ""
            run clickTags@{
                textOptions.forEach { clickTag ->
                    if (tag.contains(clickTag, true)) {
                        textToSearch = clickTag
                        return@clickTags
                    }
                }
            }
    
            return textToSearch
        }
    Is it kind of notation? does someone know it?
    e
    • 2
    • 2
  • g

    Gavin Ray

    11/30/2022, 8:08 PM
    Does anyone know of an alternative for
    ?.let { } ?: emptyList()
    that lets you place the default value at the beginning of the
    .let
    statement? One of my few complaints with Kotlin is that it becomes hard to read in cases like this:
    val foo = maybe?.null?.let {
      // really long series of statements
    } ?: someDefault()
    I'd love something like:
    val foo = maybe?.null?.letWith(someDefault) {}
    e
    k
    +2
    • 5
    • 35
  • g

    Gavin Ray

    11/30/2022, 8:08 PM
    (I know I could define an extension function but it seems so common I thought maybe there's a native/built-in for this)
  • g

    Gavin Ray

    11/30/2022, 8:09 PM
    Essentially
    .ifEmpty { }
    but for nullable values
    s
    • 2
    • 1
  • e

    Edward Muller

    11/30/2022, 10:54 PM
    New here, just saying hi. I occasionally write server side Kotlin (JVM) @ work.
  • y

    y

    12/01/2022, 9:42 AM
    when debugging and looking at the values at a breakpoint, I often get
    Unable to evaluate the expression Cannot find source class for java.util.Map
    (or
    java.util.List
    , etc.) for everything that is a `Map`/`List`/etc. only reindexing the project solves it, which is time consuming what is the cause of this issue? can I prevent it?
  • k

    KotlinLeaner

    12/01/2022, 1:22 PM
    Hi guys, which channel is best for asking for guidance of multiple api call in single screen ?
    s
    • 2
    • 3
  • d

    DK

    12/01/2022, 3:15 PM
    Hey everyone, new to programming and Kotlin. Trying to learn about classes and objects, and having a hard time understanding OOP concepts like polymorphism, inheritance, constructors etc. I'd like to remake what Google has done with the FIFA World Cup summaries of match results,fixtures,list of teams with ranking, list of players with number of goals etc. I was wondering if there was a complete project that you could point me to to help me understand how everything connects together? Appreciate any advice at all
  • d

    DK

    12/01/2022, 3:15 PM
    • 1
    • 1
  • k

    Klitos Kyriacou

    12/01/2022, 4:06 PM
    In Kotlin/JVM, is there a fast way to check if a byte array contains a given subarray? This is for a high-throughput filtering requirement. The subarray is known at design time. The byte array is UTF-8 encoded. I can convert the byte array to String and just
    String.contains
    (or
    a in b
    ), but if I can do a byte-array search instead it would be preferable as it would save the overhead of converting to String. I don't want to write a Boyer-Moore (or similar fast algorithm) implementation for this myself, as (1) I might get it wrong and (2) there may already be one and I don't want to reinvent the wheel. I'm hoping there's something already there in the stdlib.
    p
    • 2
    • 2
  • s

    Slackbot

    12/02/2022, 7:50 AM
    This message was deleted.
  • j

    Jakub Gwóźdź

    12/02/2022, 7:51 AM
    Hi there. Any protips, why is the compiler (1.7.21, JVM) complaining about “No cast needed”, when it is in fact required, because otherwise there’s `Int`/`Long` ambiguity?
    j
    e
    k
    • 4
    • 14
Powered by Linen
Title
j

Jakub Gwóźdź

12/02/2022, 7:51 AM
Hi there. Any protips, why is the compiler (1.7.21, JVM) complaining about “No cast needed”, when it is in fact required, because otherwise there’s `Int`/`Long` ambiguity?
j

Johann Pardanaud

12/02/2022, 8:01 AM
Because a short number alone is always considered to be an Int, if you want to explicitly return a Long, you can write
123L
https://kotlinlang.org/docs/numbers.html#literal-constants-for-numbers
e

ephemient

12/02/2022, 8:06 AM
that documentation doesn't cover everything. a bare literal integer can be either an
Int
or a
Long
see https://kotlinlang.org/spec/type-system.html#integer-literal-types for more details
this has been an issue with
sumOf
for as long as it has existed, https://youtrack.jetbrains.com/issue/KT-46360
j

Jakub Gwóźdź

12/02/2022, 8:09 AM
I understand the reason for need to specify Int as return type here, but I don't know why compiler complains when I do it 🙂
e

ephemient

12/02/2022, 8:11 AM
https://youtrack.jetbrains.com/issue/KT-50177 the quick fix is wrong (this should be a KTIJ bug since that's where the problem comes from)
as a workaround, you can write
0.toInt()
instead of
as Int
to force the type, but the KTIJ plugin will (falsely) show that as unnecessary too 😞
j

Jakub Gwóźdź

12/02/2022, 8:13 AM
No, the problem exist on gradle build log as well, so it's not IJ specific.
e

ephemient

12/02/2022, 8:14 AM
hmm I don't see the message in the kotlin compiler source, maybe it's a different one…
j

Jakub Gwóźdź

12/02/2022, 8:19 AM
❯ ./gradlew clean build

> Task :compileKotlin
w: /Users/jakub.gwozdz/personal/advent-of-code-2022/src/main/kotlin/day2/Day2.kt: (33, 11): No cast needed
w: /Users/jakub.gwozdz/personal/advent-of-code-2022/src/main/kotlin/day2/Day2.kt: (49, 11): No cast needed
🙂
e

ephemient

12/02/2022, 8:20 AM
ah, that makes it easy to find then. a
@Suppress("USELESS_CAST")
will stop that from showing up
j

Jakub Gwóźdź

12/02/2022, 8:26 AM
yes that’s what I did, but I was wondered why is it like so. Apparently it’s a known bug/problem, so I’m ok with that 🙂 Thanks for the help and the links
k

Klitos Kyriacou

12/02/2022, 2:55 PM
In any case, why bother with such code when you can do
lineSequence().count { it == "one" }
?
j

Jakub Gwóźdź

12/02/2022, 2:56 PM
that was just the
foo()
example 🙂
View count: 5