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
announcements
  • a

    Andrey Logoshko

    02/11/2021, 1:27 PM
    Hey guys which channel is best for kotlin-native questions?
    j
    b
    • 3
    • 3
  • d

    df

    02/11/2021, 2:45 PM
    Not sure if I am chasing ghosts but on my local machine as well as on our CI
    1L.rem(200) == 0
    compiles without errors while it should fail because rem returns Long. Using Kotlin playground the code does not compile as expected. Any idea whats going on?
    org.jetbrains.kotlin:kotlin-stdlib-jdk8:jar:1.4.30:compile
    n
    • 2
    • 1
  • b

    Brian Fox

    02/11/2021, 2:46 PM
    Is the jetbrains kotlin build pipeline team hanging around here somewhere?
    z
    • 2
    • 2
  • c

    Cdev

    02/11/2021, 7:18 PM
    I have a mutablelist of items. One of the items properties is a date value. They are currently sorted by said date value. I want to insert separator items in-between the items that have different days. What's an idiomatic way to iterate through the mutablelist list and compare the current item and the next item to see if I should insert a separator?
    k
    n
    c
    • 4
    • 8
  • m

    Marc Knaup

    02/11/2021, 8:18 PM
    Is it intentional that the compiler infers the choice between two
    <in T>
    as
    <out Any?>
    ?
    a
    • 2
    • 6
  • s

    sbeve

    02/11/2021, 9:13 PM
    what kind of optimizations could i do to this function?
    const val LOWER_CASE_LETTERS = "abcdefghijklmnopqrstuvwxyz"
    const val UPPER_CASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    
    fun rotateLetter(input: Char, rotations: Int): Char {
        val isUpperCase = input in UPPER_CASE_LETTERS
        val isLowerCase = input in LOWER_CASE_LETTERS
        var variableRotations = rotations
        var variableInput = input
    
        while (variableRotations != 0) {
            when {
                isUpperCase -> {
                    if (variableInput.toInt() == 90) variableInput = 'A'
                    else variableInput += 1
                }
                isLowerCase -> {
                    if (variableInput.toInt() == 122) variableInput = 'a'
                    else variableInput += 1
                }
                else -> return input
            }
            variableRotations--
        }
        return variableInput
    }
    n
    m
    +3
    • 6
    • 19
  • p

    Patrick Ramsey

    02/11/2021, 10:11 PM
    Possibly a dumb question, but does anyone here have experience with mockk.io, and happen to know if there’s a way to mock constructors that doesn’t result in the underlying class’s real constructor actually being called? From what I can tell (somewhat astonishingly), the default behavior of mockkConstructor() is to actually call a real constructor, then discard its output and substitute a mockk singleton. This is somewhat disappointing, since it suggests that you can’t actually mock constructors with mockkConstructor().
    l
    • 2
    • 3
  • r

    Robinnsson Cifuentes

    02/12/2021, 12:44 AM
    Hello everyone, Thank you very much for allowing me to be part of this wonderful team.
    👋 6
    n
    • 2
    • 2
  • r

    Robinnsson Cifuentes

    02/12/2021, 12:49 AM
    I apologize in advance for my English, I am in the process of learning.
    k
    • 2
    • 2
  • h

    hellman

    02/12/2021, 7:31 AM
    Good morning! Some of the kotlinx libraries are hosted on jcenter only. Since it is shutting down, what are the plans for moving those to Maven Central? See https://github.com/Kotlin/kotlinx.collections.immutable/issues/96 for instance? I wanted to remove jcenter, but I got a library with a transitive dependency to kotlinx-collections-immutable.
    j
    • 2
    • 1
  • o

    oday

    02/12/2021, 7:59 AM
    Jcenter shutting down? :O
    s
    s
    j
    • 4
    • 3
  • s

    Sudhir Singh Khanger

    02/12/2021, 8:05 AM
    val loginPage = loginPageResponseBody.loginPage
    if (loginPage != null) {
        loginPageData.postValue(loginPage)
    }
    If I am doing the null check then why does
    postValue
    method complains about requiring
    Expected non-nullable value
    . I don't get this error with
    loginPage.let { loginPageData.postValue(it) }
    .
    a
    v
    • 3
    • 10
  • e

    Eugen Martynov

    02/12/2021, 9:15 AM
    My naive implementation
    operator fun <T> T.plus(list: List<T>): List<T> {
      val result = list.toMutableList()
      result.add(0, this)
      return result
    }
    b
    g
    +2
    • 5
    • 11
  • m

    mzgreen

    02/12/2021, 11:39 AM
    I was reading about coroutines recently and I noticed that quite a lot of blog posts have links to JetBrains documentation which no loger works. For example lots of posts link to https://kotlinlang.org/docs/reference/coroutines/basics.html#structured-concurrency which doesn't work anymore. It would be cool to fix that or add a redirect to the new docs.
    v
    • 2
    • 3
  • d

    dmcg

    02/12/2021, 12:15 PM
    https://stackoverflow.com/questions/66171704/is-there-a-standard-kotlin-function-to-return-a-list-without-the-item-at-a-given
    🇳🇴 1
    m
    s
    • 3
    • 4
  • f

    Florian

    02/12/2021, 2:55 PM
    Why are non-local returns not allowed in lambdas? I can't find an explanation about the "why" anywhere
    m
    f
    o
    • 4
    • 14
  • a

    andylamax

    02/12/2021, 3:44 PM
    Hello there, Hope you are all having a blast. I am trying to understand multifield value classes so I have dumbed it down and I need some correction If I am wrong 1. Multifield value classes are like Cpp Structs, and normal classes (including data classes) are like Cpp Classes, Correct? 2. Does that translate to stack and heap allocations for Kotlin/Native?
    m
    n
    n
    • 4
    • 20
  • p

    Philip Dukhov

    02/12/2021, 3:58 PM
    I wanna my
    data class
    to have non optional field, but to be able to initialize it with a nil, which will be replaced by a default value. Something like this:
    data class Text(val text: String) {
        constructor(textNullable: String?) : this(textNullable ?: "", nullable)
    }
    It works well on native, but on JVM I got following error:
    Platform declaration clash: The following declarations have the same JVM signature (<init>(Ljava/lang/String;)V):
        constructor Text(text: String) defined in ...
        constructor Text(textNullable: String?) defined in ...
    Any way I can bypass it? I think I could replace
    data class
    with
    class
    to remove the default constructor, but in this case I’ll lose other data class advantages, like
    copy(...)
    r
    n
    a
    • 4
    • 9
  • a

    agnaldo4j

    02/12/2021, 5:28 PM
    Hi Everyone, I started an initiative to help Junior and Intermediate developers to improve their skills on Scala/Kotlin and in FP/OO programming but at this moment it's only to people that speak Portuguese, sorry about that. I will accept 3 to 5 Jr/Pl developers and we will have two meetings every week for 5 months, we will study, principles (FP and OO), microservices(ktor, finch), persistence (quill, object prevalence, spring jpa), clean architecture, etc. price: free :-), again only for Jr and Pl devs (Portuguese language) Tks everyone. If you want to join, please send me a message on linkedin: https://www.linkedin.com/in/agnaldo4j/
    w
    • 2
    • 2
  • r

    Rob Elliot

    02/12/2021, 6:12 PM
    Hey all. I’ve been pondering idly how much I miss Spock’s syntax in Kotlin, and found myself wondering whether it’s even possible to implement the same thing? Spock uses some groovy feature that allows rewriting the AST, I think.
    ➕ 1
    v
    y
    • 3
    • 7
  • s

    sbeve

    02/12/2021, 8:25 PM
    Okay so I rewrote the code, is this more optimized? how can i make stuff better
    fun rotateLetter(input: Char, rotations: Int): Char {
        var variableInput = input.toInt()
        val isUpperCase = variableInput in 65..90
        val isLowerCase = variableInput in 97..112
    
        when {
            isUpperCase -> {
                if (variableInput + rotations <= 90) variableInput += rotations
                else variableInput = 64 + (variableInput + rotations - 90)
            }
            isLowerCase -> {
                if (variableInput + rotations <= 122) variableInput += rotations
                else variableInput = 96 + (variableInput + rotations - 122)
            }
            else -> return input
        }
    
        return variableInput.toChar()
    }
    e
    a
    • 3
    • 34
  • v

    Vampire

    02/13/2021, 3:27 AM
    Why does
    javax.xml.xpath.XPathFactory.newInstance().newXPath().compile("/").evaluateExpression(null)
    give
    error: unresolved reference: evaluateExpression
    javax.xml.xpath.XPathFactory.newInstance().newXPath().compile("/").evaluateExpression(null)
                                                                       ^
    when compiling the Kotlin code using Java 11? The IDE has no problem, but if you compile it in a file or execute it in a REPL it says unresolved reference. The method was added in Java 9
    z
    a
    a
    • 4
    • 13
  • a

    Animesh Sahu

    02/14/2021, 5:58 AM
    Is there any way to distinguish these two?
    fun test(a: () -> Unit) { println("A") }
    
    fun test(a: suspend () -> Unit) { println("B") }
    
    suspend fun main() {
        test {}
    }
    According to the language i.e. if kotlin - allow suspend lambda whereas call from non-kotlin like java/js - allow normal lambda 👀
    y
    • 2
    • 18
  • m

    mending3

    02/14/2021, 12:53 PM
    spring_boot which should I choose?
    Thread()
    vs Kotlin coroutines?
    a
    • 2
    • 5
  • a

    azharkova

    02/14/2021, 4:46 PM
    Does Kotlin/Native support processing of annotations? Is it possible to provide processing in commonMain for KMM project?
    a
    • 2
    • 6
  • k

    Kirill Grouchnikov

    02/14/2021, 5:54 PM
    org.jetbrains.kotlinx:kotlinx-collections-immutable
    is still only available on jcenter / bintray. What's the right place to file a bug to move it over to Maven Central or Jetbrains' own space?
    j
    • 2
    • 2
  • m

    mending3

    02/15/2021, 4:59 AM
    update: solved adding this code to `build.gradle`:
    configure<SourceSetContainer> {
        named("main") {
            java.srcDir("src/main/kotlin")
        }
    }
    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- spring_boot
    @PostMapping("/my-endpoint")
    fun createProject(@RequestParam request: Map<String, String>): ResponseEntity<Map<String, String>> {
        val filePath = request["filepath"]
    
        try {
            val thread = thread {
    
                try {
                    MyCustomClass(filePath)
                } catch (e: Exception) {
                    when (e) {
                        is IOException, is SAXException, is ParserConfigurationException, is SQLException -> {
                            println(e)
                        }
                        else -> throw e
                    }
                } // end of thread's try
    
            }
    
            thread.start()
    
            return ResponseEntity.ok().body(
                mapOf(
                    "message" to "success"
                )
            )
        } catch (e: java.lang.Exception) {
            return ResponseEntity.badRequest().body(
                mapOf(
                    "message" to "error"
                )
            )
        }
    }
    why does spring boot give me noclassdeffound on
    MyCustomClass
    ?
    t
    • 2
    • 1
  • w

    Will Mwendwa

    02/15/2021, 8:15 AM
    Hi guys!!! Can anyone recommend for me a kotlin roadmap
    d
    • 2
    • 1
  • s

    Swanand Keskar

    02/15/2021, 1:41 PM
    Hi 👋 (@here) What is the ideal way to get hooks for method execution such as before & after to use with delegate for decorator pattern to perform some action before & after of method execution without using reflection to work with graalvm
    r
    a
    • 3
    • 4
  • n

    Niklas Gürtler

    02/15/2021, 1:57 PM
    Can I get rid of that ugly line with the
    @Suppress
    in https://pl.kotl.in/xmmqu1Wqf ? It is unreachable but without it, I get a type mismatch error.
    r
    • 2
    • 2
Powered by Linen
Title
n

Niklas Gürtler

02/15/2021, 1:57 PM
Can I get rid of that ugly line with the
@Suppress
in https://pl.kotl.in/xmmqu1Wqf ? It is unreachable but without it, I get a type mismatch error.
r

Roukanken

02/15/2021, 2:12 PM
this looks a bit better I guess? Also way more readable not sure if there is some better way
fun <T> retry (run: () -> T) : T {
    lateinit var lastError: Throwable

    repeat(5) {
        try {
            return run()
        } catch (currentError: Throwable) {
            lastError = currentError
        }
    }

    throw lastError
}

retry {
    println("Hello, world!!!")
}
compiler doesn't scream at me for the lateinit, so I guess it can figure out that it will be set 😄
🙌 1
n

Niklas Gürtler

02/15/2021, 2:15 PM
great idea, it works, thanks!!
View count: 2