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

    louiscad

    06/08/2020, 7:07 PM
    Hello, does anyone know why Kotlin kept the convention of
    alllowercasepackagenames
    from Java? What was the rationale? I'm about to name a package in camelCase because it's much more readable that way, but I'm wondering why I should follow that specific convention. EDIT: Same question for underscores (
    _
    ) in package names.
    p
    b
    +6
    • 9
    • 26
  • e

    Ellen Spertus

    06/08/2020, 10:27 PM
    I’m trying to figure out a more elegant way to write:
    if (intent.getStringExtra(SUGGESTION_KEY) != null) {
        suggestionButton.text = intent.getStringExtra(SUGGESTION_KEY)
        suggestionButton.visibility = View.VISIBLE
    } else {
        suggestionButton.visibility = View.INVISIBLE
    }
    I can’t write the following, because one arm returns a
    String
    and the other
    Unit
    :
    intent.getStringExtra(SUGGESTION_KEY)?.let { suggestion ->
        suggestionButton.text = suggestion
        suggestionButton.visibility = View.VISIBLE
    } ?: suggestionButton.visibility = View.INVISIBLE
    (I know there is a function
    intent.hasStringExtra()
    , but I’d like a general solution not specific to intents.) How should I rewrite the original block of code, or is it best as is?
    c
    b
    l
    • 4
    • 13
  • j

    jeggy

    06/09/2020, 9:50 AM
    Any reason why one is marked as a function and the other one is a method?
    m
    • 2
    • 6
  • t

    thana

    06/09/2020, 10:07 AM
    Hi, i have some class like
    class Foo<T> (val helper1: Helper1<T>, helper2: Helper2<T>)
    . here i want
    Helper1
    and
    Helper2
    work on the same type
    T
    but in fact
    Foo
    doesn't really care about what
    T
    actually is - they just must match. Is there a way not having to declare the
    T
    on
    Foo
    itself? I don't want to write something like
    Foo<*>
    everywhere i'm using
    Foo
    Or maybe the better question: i sense there is some design flaw here but i cannot really put the finger on. What approaches are there, to resolve this flaw?
    e
    d
    l
    • 4
    • 11
  • d

    dead.fish

    06/09/2020, 10:18 AM
    Hi all! I was under the impression that
    KClass::sealedSubclasses
    is not only part of the API of Kotlin 1.3, but also of it’s implementation, but apparently this needs
    kotlin-reflect
    . Now I’m on a constrained device and would rather not add a 2.7MB lib just for that. Are there alternatives (beside going back to a good old
    enum class
    )?
    c
    • 2
    • 2
  • l

    LastExceed

    06/09/2020, 11:03 AM
    ::main
    in line 4 gives a an overload resolution ambiguity. I understand why it happens, but how do i resolve it? (i'd like to know the solution to both scenarios)
    Untitled
    b
    e
    • 3
    • 3
  • i

    iex

    06/09/2020, 4:09 PM
    is there anything out of the box to convert code that can throw an exception to
    Result
    ?
    b
    • 2
    • 4
  • t

    Twferrell

    06/09/2020, 4:52 PM
    z
    • 2
    • 15
  • c

    Colton Idle

    06/09/2020, 11:59 PM
    I'm trying to figure out an issue I have with dagger + kotlin. I have a class
    @Module
    class NetworkModule constructor(@Inject public var url: String)
    but when I look at the decompiled code in java I see:
    public final class NetworkModule {
       @Inject
       @NotNull
       private String url;
    This is the error I'm trying to figure out "error: Dagger does not support injection into private fields private java.lang.String url;" Not necessarily a dagger issue, but somehow creating a private field in java even though I specify it to be public in kotlin?
    j
    d
    • 3
    • 3
  • x

    xii

    06/10/2020, 12:11 AM
    how do you folks add constraints to your data classes? say if parameter a is null then b cant be not null
    d
    m
    • 3
    • 4
  • m

    Mark

    06/10/2020, 4:11 AM
    Which do you prefer? 1.
    for (value in map.values) { … }
    2.
    for ((_, value) in map) { … }
    1️⃣ 18
    n
    m
    +2
    • 5
    • 5
  • g

    GarouDan

    06/10/2020, 12:02 PM
    Hi, I’m creating a kotlin library and I’d need to create a lot of functions. Is there a way to get (programatically) all keywords used in kotlin? I’ll need to escape then with backticks `. One example is the
    continue
    keyword that should become ``continue`` when I escape.
    e
    m
    • 3
    • 8
  • l

    LastExceed

    06/10/2020, 3:32 PM
    listOf("banana").map { it to 42 }.toMap()
    is there an easier way to do this ? basically i want to turn a list into a map by providing a lambda that associates each element from the list with a value to form a key-value pair
    s
    c
    d
    • 4
    • 7
  • i

    iex

    06/10/2020, 5:53 PM
    Can I pattern match a
    Pair<T, T>
    (or tuple in general), whose elements are case classes? (I need to pattern match the subtypes of the sealed class)
    s
    • 2
    • 2
  • h

    herlevsen

    06/10/2020, 8:42 PM
    Hi. Is it not kinda weird that a Set in Kotlin allows duplicates when mapping over the set? https://pl.kotl.in/r9b-MCq8p 😮
    z
    s
    j
    • 4
    • 6
  • g

    GarouDan

    06/10/2020, 11:31 PM
    How can we create a 
    !
     operator in Kotlin? For example, if I have MyClass defined as:
    MyClass() {
      run() {
        println("finished")
      }
    }
    I’d like to create a situation where doing something like this:
    val myObject = MyClass()
    myObject!
    is equivalent to
    myObject().run()
    the methods will be more complex since this is for a special library that I’m doing, but the simple idea is like this. How can we define this operator? I think it is possible because we have the 
    !!
      one.
    d
    z
    +3
    • 6
    • 13
  • b

    Barddo

    06/11/2020, 12:59 AM
    I'm looking for projects to contribute, does anyone know some?
    m
    • 2
    • 2
  • e

    edenman

    06/11/2020, 4:03 AM
    Anybody know if there’s some way to do
    TimeMark.elapsedSince(other: TimeMark)
    ? or plans to add it?
    j
    n
    • 3
    • 15
  • d

    Dibya Ranjan

    06/11/2020, 5:04 AM
    Hi Folks, I saw this article by Roman, https://medium.com/@elizarov/kotlin-and-exceptions-8062f589d07 I had been a Java developer and started adopting Kotlin few weeks back. Most of my code is very similar in terms of what I would write in Java 11. I am quoting Roman here
    *As a rule of thumb, you should not be catching exceptions in general Kotlin code.* That's a code smell.
    . I see that I can make changes to my APIs to validate and return rather than throwing and catching an exception. However, I failed to come up with a better code for one scenario. I have a Kafka consumer, which makes a call to a web API. so I have
    onListen(p: Person) -> orchestrator(p: Persons) -> makeRestCall(p: Person) -> API
    the exception flow here as I would do in Java is to handle all non response codes 200s. If there is an error returned from the API, I throw and exception, the orchestrator catches it. Is this an anti pattern in Kotlin? I think I am not the first person to have this issue, it would be of great help if someone can give a direction here. Thank you.
    h
    e
    b
    • 4
    • 11
  • s

    Stephen Prochnow

    06/11/2020, 7:20 AM
    Hi, I have a pretty basic question: What are the practical uses/ advantages of Boolean functions like
    and(), or(), not()
    over Boolean operations like
    &&, ||, !
    . Thank you in advance for your answers.
    e
    t
    j
    • 4
    • 9
  • l

    LastExceed

    06/11/2020, 10:27 AM
    is there a way to do this less copy-pasty that isn't completely over-engineered ?
    Untitled
    a
    b
    • 3
    • 5
  • p

    Philipp Mayer

    06/11/2020, 10:44 AM
    Hey guys, I have a value object which holds a string:
    data class SystemName(val value: String) {
        init {
            require(value == value.toLowerCase().capitalize()) { "Name $value must be capitalized!" }
        }
    Right now, when I create the Object I always check if its lowercase with the first letter being capital. I'd like to let the object take care of
    .toLowercase().capitalize()
    , so I don't have to do it on my own. Searching google gives me mixed results which don't look that clean tbh. What would be your take on this? Thanks ahead! My current take is the following:
    data class SystemName(val value: String) {
        init {
            require(value == value.toLowerCase().capitalize()) { "Name $value must be capitalized!" }
        }
    
        /**
         * automatically converts string to required format
         */
        companion object {
            fun createInstance(name: String) = SystemName(name.toLowerCase().capitalize())
        }
    h
    m
    • 3
    • 18
  • m

    mplain

    06/11/2020, 12:30 PM
    Hi! 🙂 I have a Matrix class with a primary constructor that takes two integer arguments (rows and columns) and a supplier function that tells it how to get its next element based on its indices:
    class Matrix<N : Number>(private val rows: Int, private val columns: Int, f: (Int, Int) -> N) : List<List<N>>
    by List(rows, { i -> List(columns) { j -> f.invoke(i, j) } }) {
    Now I want to add a secondary constructor that would take an iterable (list or array) of elements, like this:
    constructor(rows: Int, columns: Int, values: Iterable<N>) {
        val iterator = values.iterator()
        Matrix(rows, columns) { _, _ -> iterator.next() }
    }
    This doesn't work, says "call to primary constructor expected" Any advice on how to address this problem, Kotlin-style?
    j
    • 2
    • 32
  • n

    nicholasnet

    06/11/2020, 7:20 PM
    Hey guys! I am working on Spring Reactive using Kotlin. I am trying to find the best solution to get the
    id
    property value of generic
    T
    this is my code.
    class BaseRepository(val client: DatabaseClient, val dataAccessStrategy: ReactiveDataAccessStrategy) {
    
        suspend inline fun <reified T> save(entity: T): T {
    
            val id = // How to get the id of entity?
            try {
    
                return client.insert()
                             .into(T::class.java)
                             .using(entity)
                             .map(dataAccessStrategy.converter.populateIdIfNecessary(entity))
                             .awaitOne()
    
            } catch (exception: Exception) {
    
                throw exception
            }
        }
    }
    What is the best approach to get the id of entity here?
    b
    m
    e
    • 4
    • 4
  • s

    Shawn Karber_

    06/11/2020, 10:45 PM
    im trying to figure out the best way to write some code for a library. in Elixir I used to be able to do something like:
    def is_ten(x) when x > 10, do: "Greater than ten"
    def is_ten(x) when x < 10, do: "Less than ten"
    I need to write a kotlin function that always takes a string, but the logic is completely different based on that string, is there a way to encapsulate logic into a function that is called based on the parameter value similar to elixir guard clauses?
    n
    j
    • 3
    • 7
  • o

    Oleg Siboglov

    06/12/2020, 2:50 AM
    Hey all. I’m wondering how this exception
    java.lang.NullPointerException: Attempt to invoke virtual method 'float java.lang.Number.floatValue()' on a null object reference
    can occur while iterating over a
    MutableList<Float
    . All
    Float
    values that are added to the list are
    nonNull
    ; a
    Float
    value is returned from one function (where the return type is
    Float
    ), used by a different function (where the parameter type is
    Float
    ), and then added to the
    MutableList<Float>
    . Later I iterate over the list (
    for (i in 0 until list.size) list[i]
    ) and it is here when the exception is thrown, when I’m getting the values from the list. I’ve only ever seen this happen once from crashlytics, but I cannot understand how it even happened once. Values are only added to the list at one point in my execution. After adding values to the list, and before iterating over the list, I may remove the last value in the list (
    list.removeAt(list.size - 1)
    ). Looking at the decompiled code (
    ((Number)this.list.get(index)).floatValue()
    ) tells me that the value at that index is null. Am I misunderstanding the stack trace? Could someone please clear this up for me?
    z
    j
    e
    • 4
    • 3
  • v

    Victor Harlan Lacson

    06/12/2020, 8:21 AM
    Hello everybody, I wanted some help on multi-platform project, on build.gradle.kts jvm target is set to 1.8 but when i run test errors keeps popping out: Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. any ideas why im getting this?
    d
    j
    • 3
    • 15
  • u

    user

    06/12/2020, 11:12 AM
    message has been deleted
    k
    • 1
    • 1
  • g

    Gayan Perera

    06/12/2020, 4:55 PM
    Hi all, can i know the plan for kotlin-eclipse plugin ? I see that there is no recent activities on the plugin repo.
    j
    h
    m
    • 4
    • 5
  • g

    GemiDroid

    06/12/2020, 7:56 PM
    Hello everyone, is Kotlin navigating to cross-platform way or I am wrong..and if someone explains, plz ?
    s
    m
    • 3
    • 2
Powered by Linen
Title
g

GemiDroid

06/12/2020, 7:56 PM
Hello everyone, is Kotlin navigating to cross-platform way or I am wrong..and if someone explains, plz ?
s

Shawn

06/12/2020, 8:14 PM
what do you mean? #multiplatform is already a thing
m

Matteo Mirk

06/15/2020, 10:25 AM
Kotlin is already aimed towards multi-platform since long time. Each new release brings improvements to the standard library in terms of common code for all supported platforms and the work on Kotlin/Native is impressive and getting better and better. Have a read here: https://kotlinlang.org/docs/reference/multiplatform.html If you’re referring to just mobile cross-platform read here: https://www.jetbrains.com/lp/mobilecrossplatform/
View count: 1