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

    Jason Inbody

    02/18/2021, 6:29 PM
    I'm completely new to Kotlin and I need to rewrite a cross platform app to be native. I've already finished the Swift UI side and loved the declarative UI style. I saw Kotlin had entered beta with Jetpack Compose with their version of declarative UI. I understand it's in beta but how fluid is it it to use? I need to use Google maps and also braintrees drop in payment UI. SwiftUI had was to make representable views from UIKit incase you got in a corner with something that wasn't supported. Does Compose have something like that? I know for a fact there's no braintree support for Kotlin Compose but can you mix a Java view, wrap it in Kotlin and then add it to a compose view? I'm just trying to feel out if there's work arounds incase I would get stuck where there's no support
    a
    • 2
    • 2
  • d

    Daronee

    02/19/2021, 12:48 AM
    Could anyone help me out with reading from the InputStream? Whenever I receive the data and put it into a buffer, the elements in it seems to be inconsistent. For example I am expecting a buffer of [0,0,0,0,0,0,4,3,0]. sometimes I get the right values sometimes I get [0,0,0,0,0,0,3,0,0], or [0,0,0,0,0,0,0,3,4] or some different variation. I am not entirely sure if there is not enough time to update the buffer properly before it is being evaluated or if there is some other problem. This is being done within a
    run()
    function of a thread Its like the app is receiving the data from the inputstream consistently. It always varies Seems to be a problem when the number of bytes > ~6 for some reason?
    j
    • 2
    • 2
  • c

    Colton Idle

    02/19/2021, 5:35 PM
    Just wanted to see if anyone knows of an idiomatic way of adding a
    ,
    between strings in a string builder. I know
    joinToString
    exists and it works great for arrays, but I basically want the same functionality for a string builder. Here's what I'm currently doing (no commas yet):
    topic.data.forEach {
                        myBuilder.append("${it.city} ${it.status}")
                    }
                }
    Maybe I'm missing something basic. Thanks
    v
    n
    • 3
    • 13
  • p

    poohbar

    02/20/2021, 8:03 PM
    how to make a function with one input parameter which returns the same type but retains nullability in a generic way? e.g.
    T -> T
    and
    T? -> T?
    e
    • 2
    • 4
  • p

    poohbar

    02/20/2021, 8:22 PM
    how to call a java function called
    to
    from Kotlin? it keeps trying to use the
    Pair
    extension 🤔
    y
    d
    n
    • 4
    • 6
  • m

    Melvin Biamont

    02/21/2021, 6:06 PM
    Hello, I have a question regarding generics. I would like to store lambdas into a Map. And those lambdas have a generic parameter. So, I did this simple code
    typealias AFunction<R, A> = suspend (args: A) -> Result<R>
    
    val functionMap = mutableMapOf<String, AFunction<Any?, Any?>>()
    
    fun <R, A> addFunctionToMap(name: String, function: AFunction<R, A>) {
        functionMap[name] = function
    }
    For some reasons, it doesn’t compile (on the line
    functionMap[name] = function
    ) as it is saying it was expecting a type
    AFunction<Any?, Any?>
    and not
    AFunction<R, A>
    . I tried modifying a bit the
    addFunctionToMap
    function like this:
    fun <R: Any?, A: Any?> addFunctionToMap(name: String, function: AFunction<R, A>) {
        functionMap[name] = function
    }
    But, it doesn’t change the compiler error. Do you have an idea how I could solve that? 🙏
    t
    r
    m
    • 4
    • 6
  • m

    Mark

    02/22/2021, 3:43 AM
    When building an abstract class where you want the subclasses to provide some property, how would you decide between constructor arg versus abstract val?
    a
    • 2
    • 12
  • g

    gabrielfv

    02/23/2021, 5:33 PM
    Has anybody successfully managed to run linters with type resolution as triggers on their projects? Either CI after build or as pre-commit/pre-push git hooks?
    🇧🇷 1
    • 1
    • 1
  • p

    Pedro Alberto

    02/25/2021, 7:21 PM
    Hi guys I'm participating on the AndroidDevChallenge and I do not know why my code is failing on UI test remotely
    :are-you-kidding-me: 1
    😅 1
    😀 1
    c
    • 2
    • 6
  • s

    Sudhir Singh Khanger

    02/27/2021, 3:30 AM
    // generated by JsonToKotlinClass
    data class JsonToKotlinClass(
        val `data`: List<Data?>?
    ) {
        data class Data(
            val id: Int?
        )
    }
    
    // generated by RoboPOJOGenerator
    data class RoboPOJOGenerator(
        val data: List<DataItem?>? = null
    )
    
    data class DataItem(
        val id: Int? = null
    )
    
    fun main() {
        val jsonToKotlinClassData: JsonToKotlinClass.Data = JsonToKotlinClass.Data(1)
        val roboPOJOGeneratorData: DataItem = DataItem(1)
    }
    The former is generated by JsonToKotlinClass plugin and latter is generated by RoboPOJOGenerator. Which one would you prefer? Besides differences in syntax and how they are used are there other pros and cons of these two approaches.
    j
    n
    • 3
    • 6
  • d

    dephinera

    03/01/2021, 9:21 AM
    I'm dealing with function overloading when the parameters are lambdas and stumbled upon the following case:
    fun foo(block: String.(String) -> Unit) {
    
    }
    
    fun foo(block: () -> Unit) {
    
    }
    
    fun main() {
        foo { it: String ->
            // calls foo(block: String.(String) -> Unit)
        }
        
        foo { // ERROR
            // how to call foo(block: () -> Unit)
        }
    }
    Basically is there a way to specify in the second case that I want to call
    foo(block: () -> Unit)
    . When I specified the type of the lambda argument, it seemed that the compiler was able to figure it out, however
    it: Unit
    doesn't work for the second case.
    s
    y
    a
    • 4
    • 7
  • c

    Cicero

    03/01/2021, 2:17 PM
    Where to start as a java developer: Kotlin for Java Developers | Coursera Kotlin for Java developers | Android Developers I would recommend having something like this pinned in the getting-started, it’s not the first time I see this sort of question coming around :)
    y
    • 2
    • 2
  • t

    therealbluepandabear

    03/01/2021, 11:34 PM
    I am having a hard time understanding lambda expressions in Kotlin...
    c
    a
    +2
    • 5
    • 4
  • t

    therealbluepandabear

    03/02/2021, 5:26 AM
    Also I have this question which I hope you could answer: when should I use nullable types in Kotlin? Should you always use nullable types or just when they are needed? I am a bit confused. Thank you.
    i
    m
    c
    • 4
    • 5
  • c

    Colton Idle

    03/03/2021, 4:01 AM
    I feel like I found conflicting info on how to add a code snippet to a kdoc for my function. @yole in an old SO post said to just use triple backticks
    But kdoc documentation currently links out to <https://daringfireball.net/projects/markdown/syntax#precode> which seems to say that you should just indent?
    
    Which one is correct?
    
    I just want to have something like this
    
    ```/**
    * Sample usage
    * ```kotlin
    * blah.boop()
    *
    */``` Is that correct? I thought I would maybe get some syntax highlight in the IDE, but nothing. Is having the kotlin keyword following the backticks not needed?
    e
    • 2
    • 4
  • t

    therealbluepandabear

    03/03/2021, 5:05 AM
    Is there a more concise way of doing the following:
    fun main() {
        println(alternatingCase("hello kotlin"))
    }
    
    fun alternatingCase(param: String) : String {
        val array: CharArray = param.toCharArray()
        var newString = ""
        for ((index, char) in array.withIndex()) {
            newString += if (index % 2 != 0) char.toUpperCase() else char.toLowerCase()
        }
        return newString
    }
    c
    w
    +3
    • 6
    • 7
  • b

    Brian Carr

    03/03/2021, 8:03 PM
    Hello all, is there a way to do one of the two following things? 1. in a normal blocking function, determine if the function was called from a coroutine context 2. Warn a user in a meaningful way that they should not call a specific blocking function from a coroutine context (ideally by failing to compile as if i tried to call a suspend fun from a blocking fun, but a really good warning is good enough for me) I know that if I add a false
    @Throws(IOException::class)
    to my method, it gets highlighted as an inappropriate blocking call in IDEA, and I can just add docs to the method and hope people read them when they get the unrelated warning. However, I’m hoping for something a little more direct. Anyone have any ideas or pointers?
    🤔 2
    e
    • 2
    • 2
  • t

    therealbluepandabear

    03/04/2021, 1:03 AM
    Any1 know how one can code with Kotlin on a chromebook
    e
    p
    • 3
    • 6
  • c

    crummy

    03/04/2021, 7:58 AM
    how come this doesn't smartcast the result of first to a String?
    val l = listOf<Any>("foo")
    l.first { it is String}.length // unresolved reference: length
    And is there a way to get this to work with a smartcast?
    y
    b
    +2
    • 5
    • 5
  • s

    Sudhir Singh Khanger

    03/08/2021, 4:12 AM
    package leetcode
    
    import kotlin.collections.set
    
    fun main() {
        val nums1 = intArrayOf(1, 2, 2, 1)
        val nums2 = intArrayOf(2, 2)
        println(intersect(nums1, nums2).joinToString())
    }
    
    fun intersect(nums1: IntArray, nums2: IntArray): MutableList<Int> {
        val outputMap = hashMapOf<Int, Int>()
        val outputList = mutableListOf<Int>()
    
        for (i in nums1.indices) {
            if (nums1[i] in outputMap) {
                outputMap[nums1[i]]++
            } else {
                outputMap[nums1[i]] = 1
            }
        }
    
        for (i in nums2.indices) {
            if (nums2[i] in outputMap && outputMap[nums2[i]] > 1) {
                outputList.add(nums2[i])
                outputMap[nums1[i]]--
            }
        }
    
        return outputList
    }
    outputMap[nums1[i]]++
    is complaining that
    No set method providing array access
    . I am not sure why.
    e
    t
    j
    • 4
    • 5
  • e

    Eivind

    03/08/2021, 8:47 AM
    Is there a easy way of getting maven dependensys in the Kotlin repl or is download and starting whit the -cp arg the only way?
    v
    • 2
    • 2
  • t

    therealbluepandabear

    03/09/2021, 1:49 AM
    I am just getting started with Kotlin.. How would I parse an XML file into a List of String? Coming from a C# background, the .NET framework was extremely rich with its parsing.
    :java: 1
    :google: 9
    :stackoverflow: 6
    c
    r
    • 3
    • 2
  • j

    JungIn Choi

    03/09/2021, 11:00 AM
    Hi people, I’m glad there’s a community channel to ask a question :D I’m a super newbie for Kotlin (I installed IntelliJ yesterday🙄) I have basics in Java by the way I’m just curious why println does not work inside for loop. Is this intended or is it just a bug in this IntelliJ IDE?
    for ((index, element) in swarm.withIndex()){
         println("Fish at $index is $element")
     }
    Fish at 0 is 12Fish at 1 is 5
    👋 1
    h
    j
    • 3
    • 4
  • t

    therealbluepandabear

    03/10/2021, 2:06 AM
    Hi... I've been trying to find a solution to this - I was wondering if someone could work with me regarding this; rather new to Kotlin. I'm analysing a lot of words. I am trying to find the word which contains the most unique letters from (A-Z) and return it. Does anyone know a way to do this in Kotlin? I've been trying to for quite some time. Haven't seemed to find a way yet. Tom
    y
    m
    • 3
    • 3
  • c

    Conor Fennell

    03/11/2021, 5:30 PM
    Howdy, What would be the idiomatic Kotlin way to go here?
    data class Calculation(
        val money: Double,
        val multiplier: Double,
    )
    fun Calculation.total(): Double = money * multiplier
    OR
    data class Calculation(
        val money: Double,
        val multiplier: Double,
    ) {
        fun total(): Double = money * multiplier
    }
    w
    e
    • 3
    • 3
  • t

    Tom Niesytto

    03/12/2021, 7:58 AM
    Howdy from Austin, TX.
    👋 9
    c
    • 2
    • 1
  • d

    Daniele B

    03/12/2021, 6:12 PM
    What’s the best way to modify a nested property in an immutable data class object?
    data class AppState (
        val masterState : MasterState = MasterState(),
    )
    data class MasterState (
        val isLoading : Boolean = false,
    )
    is there a more concise way than this?
    val myState = AppState()
    val newState = myState.copy(masterState = myState.masterState.copy(isLoading = true))
    e
    • 2
    • 7
  • d

    Daniele B

    03/12/2021, 8:25 PM
    I would like to use a block function like this one inside an extension function:
    fun MyModel.anExtensionFunction() {
    	objectLambda {
    	     it.getText()
    	}
    }
    where it is the obj property of the MyModel class How should I write the objectLambda function in order to do so?
    class MyModel {
        var obj = MyObject()
        fun objectLambda() {
             // HOW SHOULD I WRITE THIS FUNCTION?
        }
    }
    
    class MyObject {
        fun getText() = "myText"
    }
    e
    • 2
    • 3
  • u

    ursus

    03/14/2021, 8:02 PM
    How can I make the IDE to create this lambda for me? I hate myself writing that manually
    j
    v
    • 3
    • 5
  • h

    huehnerlady

    03/16/2021, 10:26 AM
    Hi. I would like to get the qualified name of a typealias. I have an alias
    typealias my.test.Foo = String
    I would now like to get the quaifiedName, so
    my.test.Foo
    . but using
    Foo::class.qualifiedName
    I get
    kotlin.String
    . I found this in a proposal, but the issue to it is closed and unfortunately
    Foo::typealias.qualifiedName
    does not work. Is there another way? I am currently on version
    1.4.21
    r
    • 2
    • 1
Powered by Linen
Title
h

huehnerlady

03/16/2021, 10:26 AM
Hi. I would like to get the qualified name of a typealias. I have an alias
typealias my.test.Foo = String
I would now like to get the quaifiedName, so
my.test.Foo
. but using
Foo::class.qualifiedName
I get
kotlin.String
. I found this in a proposal, but the issue to it is closed and unfortunately
Foo::typealias.qualifiedName
does not work. Is there another way? I am currently on version
1.4.21
r

Ruckus

03/16/2021, 2:07 PM
No, it's just an alias. It doesn't exist at runtime.
😞 1
View count: 4