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

    Tuang

    09/25/2019, 8:58 AM
    what does this
    handler: (key: K) -> V?)
    means In the following function
    fun getOrPut(key: String, handler: (key: String) -> V?)
    i thinks
    handler
    is something likes the arguments name, so what are the rest? is it a lambda ?
    d
    d
    +2
    • 5
    • 15
  • s

    Sylvain Patenaude

    09/25/2019, 6:59 PM
    Ok, I'm new to Kotlin, so just want to validate some info. My goal is to write a library (or SDK/API) in Kotlin Multiplatform that will be consumed by native mobile clients in either Android (Kotlin, Java) or iOS (Swift, Objective-C). From what I understand, the generated SDK artifact would be a .framework file for iOS consumers and a .jar file (or .class files) for Android consumers, is this correct? Thanks in advance!
    d
    • 2
    • 7
  • k

    Kenneth

    09/26/2019, 10:42 AM
    Is there a kotlinfied
    Character.getNumericValue()
    ?
    v
    d
    +2
    • 5
    • 9
  • m

    Martin Nordholts

    09/26/2019, 1:05 PM
    Is there something like Pythons 3.8 f-string = syntax in Kotlin? I.e. with
    val foo="bar"
    I would like to not have to write the
    foo=
    part in
    "foo=$foo"
    in order to get the string
    foo=bar
    , but, like in Python, perhaps like this instead:
    "${foo=}"
    but that gives me compilation errors in Kotlin version 1.3.41 (JRE 1.8.0_221-b11)
    k
    • 2
    • 2
  • s

    Shawn

    09/26/2019, 9:01 PM
    https://kotlinlang.org/docs/reference/generics.html#declaration-site-variance
    f
    • 2
    • 8
  • s

    Sylvain Patenaude

    09/26/2019, 9:04 PM
    Noob question #237: Can you write an MPP library targeting iOS (among others), so that it would output a .framework file, using IntelliJ for Windows?
    🇳🇴 1
    😮 1
    • 1
    • 1
  • j

    Josh Taylor

    09/27/2019, 12:27 AM
    Hey, I'm working on a project that is a addon to a java program, to make it work I have to shade in kotlin-stdlib but that makes the output jar come out to ~8mbs, anyone know a way to only shade in whats actually used? Thanks for the help using maven shade plugin
    m
    • 2
    • 1
  • u

    ursus

    09/27/2019, 2:38 AM
    Hi, is there some collection api that trims a mutable list to a size? I know
    take
    but that creates a new list
    d
    k
    • 3
    • 5
  • u

    ursus

    09/27/2019, 2:42 AM
    but it should be maybe more efficient, i.e. just trim the underlying array
    n
    • 2
    • 5
  • u

    ursus

    09/27/2019, 3:41 AM
    that has to be super ineffecient, right?
    m
    t
    • 3
    • 3
  • a

    andym

    09/27/2019, 3:01 PM
    I should mention this is using Kotlin-1.3.0
    k
    • 2
    • 6
  • t

    Tuang

    09/29/2019, 4:17 AM
    I need some advice for my following code.
    import java.time.Duratio
    
    class SimpleObjectCache (val cacheDuration: Duration)  {
        private val cacheManager = if (cacheDuration.getSeconds().toInt() <= 2147483647) SimpleObjectCacheManager(cacheDuration.getSeconds().toInt()) else throw IllegalArgumentException("cacheDuration Int value is out of range")
    It is simple, i hope you got what i m doing is.
    cacheManger
    is too long right? 😁 Is there any better way? 🤔
    k
    • 2
    • 4
  • v

    Vague

    09/30/2019, 10:32 AM
    Read through Kotlin's docs, can you recommend any other resource that can take me indepth Kotlin? Thanks!
    m
    m
    • 3
    • 3
  • r

    Rick Pendrick

    09/30/2019, 3:00 PM
    I am curious, in this code:
    fun String.asIndex(): Int = withIndex().sumBy { ... }
    Why does the call to withIndex() not need use "it" or "this" ? <<I am newbie, obviously!>>
    m
    • 2
    • 3
  • r

    Rick Pendrick

    09/30/2019, 3:00 PM
    to*
    m
    • 2
    • 3
  • s

    skendrick

    09/30/2019, 3:39 PM
    I’m trying to count the diffs in two equal-lengthed strings. My approach is to reduce one string into an int, using the index to compare chars in the other string. Maybe I’m just thinking about this too much like JS?
    str1 = "ABC"
    str2 = "ABB"
    diff = 1
    // JS
    str1.reduce((accumulator, currLetter, index) => {
          if (currLetter !== str2[index])  return accumulator + 1
    }, 0)
    Is this a kotlin-y way to approach the problem or am I being a dingus?
    s
    p
    • 3
    • 9
  • e

    Ellen Spertus

    09/30/2019, 9:06 PM
    I’m thinking functional style and, rather than overwriting the current state of my object, a colleague suggested I append the latest state to a list, so I never overwrite/throw away information.
    s
    b
    • 3
    • 8
  • s

    serebit

    09/30/2019, 9:07 PM
    :thread-please: Use threads, please
    :thread-please: 3
    e
    • 2
    • 2
  • v

    vinny2020

    09/30/2019, 9:28 PM
    I’m a longtime Java developer and have always wanted to build Android apps but never seem to get the time. Also want to learn more about Kotlin. Can I kill 2 birds with one stone by starting off using Kotlin for Android apps to keep my interest going? Or should I start with a more general overview of the programming language first to avoid missing fundamentals?
    a
    • 2
    • 7
  • v

    Vinicius Araujo

    09/30/2019, 10:03 PM
    Writed this code but looks just like java with different sintax, what would be a kotliner way to write such function?
    fun StringValues.getUuidParam(name: String): UUID {
        val id = getAll(name)?.firstOrNull() 
        if(id != null)
            try {
                return UUID.fromString(id)
            } catch (e: InvalidArgumentException) {
                httpException(developerMessage = "Parameter $name does not contain a valid UUID")
            }
        else
            httpException(developerMessage = "Required param $name is not present")
    }
    a
    a
    +2
    • 5
    • 12
  • v

    Viet Hoang

    10/01/2019, 8:18 AM
    Why does this code work
    fun String?.whenNotNullOrEmpty(callback: (String) -> String?): String? {
        return if (this.isNullOrEmpty()) null
        else callback(this)
    }
    but this doesn’t ?
    fun String?.whenNotNullOrEmpty(callback: (String) -> String?): String? {
        return if (isNullOrEmpty()) null
        else callback(this)
    }
    s
    d
    • 3
    • 3
  • c

    Colton Idle

    10/02/2019, 3:02 AM
    I still find myself doing something like:
    if (viewModel.value?.items()?.subItems != null) {
        //Do my thing
    }
    I don't think this is bad because it's straight forward. As long as that statement is not null I want to execute some code. Is there a more idiomatic way of doing this?
    a
    a
    +2
    • 5
    • 7
  • e

    Ellen Spertus

    10/02/2019, 6:18 PM
    Is there a way to access an instance variable from an inner class of a sealed class? Here’s a code excerpt:
    class NearbyConnection{
    
        var connectionsClient: ConnectionsClient = Nearby.getConnectionsClient(context)
        
        public sealed class ConnectionState(val name: String) {
            inner class Authenticating: ConnectionState("authenticating") {
                fun accept() {
                    connectionsClient.acceptConnection(neighborId, payloadCallback)
                    updateState(ConnectionState.Connecting(neighborId, neighborName))
                }
            }
    I am getting the error “unresolved reference connectionsClient” within the function.
    k
    k
    • 3
    • 8
  • p

    Prajjawal Banati

    10/03/2019, 7:19 AM
    I am quite new to this slack as well as Kotlin. In this platform we can ask doubts related to the code but can anyone tell me that from where should I start. I know learning any coding language has endless concepts but till what I must do to be a successful kotlin developer ?
    m
    a
    • 3
    • 3
  • e

    Ellen Spertus

    10/03/2019, 7:21 PM
    I’m trying to use reflection to get the name of classes extending a sealed class, but I always get the name of the sealed class (
    ConnectionState
    ). Here’s my code:
    public sealed class ConnectionState() {
            var name = ConnectionState::class.simpleName ?: "null"
    
            object Isolated : ConnectionState()
            object Advertising : ConnectionState()  
            object Discovering : ConnectionState()
       }
    Any advice?
    r
    • 2
    • 6
  • s

    Slackbot

    10/04/2019, 6:40 AM
    This message was deleted.
    k
    k
    • 3
    • 3
  • f

    Florian

    10/04/2019, 8:25 AM
    are top-level variables outside of a class referred to as "properties"?
    m
    m
    m
    • 4
    • 12
  • f

    Florian

    10/04/2019, 2:44 PM
    val a
    get() = Random().nextInt(10)
    Is this the only situation a
    val
    can return a different value each time it is accessed? (obviously the Random function is replaceable)
    a
    t
    k
    • 4
    • 4
  • f

    Florian

    10/04/2019, 2:57 PM
    also, how do you access a top-level variable outside a class when there is another one with the same name inside the function
    l
    a
    • 3
    • 8
  • f

    Florian

    10/04/2019, 7:01 PM
    can someone give me a simple explanation why they didn't just use
    const
    as a standalone keyword instead of
    const val
    ? There is no other
    const
    combination as far as I see it
    ➕ 1
    k
    i
    a
    • 4
    • 24
Powered by Linen
Title
f

Florian

10/04/2019, 7:01 PM
can someone give me a simple explanation why they didn't just use
const
as a standalone keyword instead of
const val
? There is no other
const
combination as far as I see it
➕ 1
k

Kirill Zhukov

10/04/2019, 7:35 PM
`const`s are assigned in compile time, `val`s are assigned in runtime.
Which is why you can only assign primitives and strings to a
const
, and can’t assign function results.
But I guess your question is more about why not just
const
?
f

Florian

10/04/2019, 7:40 PM
yep, why not just const
k

Kirill Zhukov

10/04/2019, 7:51 PM
const
is a modifier in this case, where as
val
is a keyword.
val
indicates a value that cannot be reassigned and by default it’s assigned in runtime.
In comparison
const
is a modifier to a
val
keyword, it says how the value is being assigned.
It’s very similar to visibility modifiers
you have
class
keyword and
private
modifier
having some sort of
privateClass
keyword (since we have functions and other things) would be redundant, if it makes sense
Having
const
is more flexible this way
And less overlapping
f

Florian

10/04/2019, 7:55 PM
ok, but why didn't they make it a keyword when it's never used in another context?
k

Kirill Zhukov

10/04/2019, 7:58 PM
Flexibility
I saw some discussions around being able to apply
const
modifier on functions
f

Florian

10/04/2019, 8:00 PM
so they want to keep the possibility open?
Right now
const
can't be used somewhere else, or can it?
k

Kirill Zhukov

10/04/2019, 8:00 PM
That’s my understanding
Yeah, I don’t think it can be used elsewhere currently
f

Florian

10/04/2019, 8:05 PM
ok, thank you very much
i

ilya.gorbunov

10/04/2019, 8:56 PM
const
is a soft keyword, that means it can be used in other places just as a usual identifier, e.g.
val const = kotlin.random.Random.nextInt()
println(const)
k

Kirill Zhukov

10/04/2019, 9:02 PM
neat
f

Florian

10/04/2019, 9:46 PM
but that's not the reasoning behind that is it?
It's just a side-effect
a

arekolek

10/05/2019, 10:01 AM
AFAIK, having as few hard keywords as possible is one of the goals
View count: 6