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

    bjonnh

    04/27/2019, 7:45 PM
    Looks like the problem above is due to the constructor. There is something is spring data that doesn't like this class to have a constructor.
    p
    n
    s
    • 4
    • 6
  • u

    ursus

    04/29/2019, 3:02 AM
    val foo1: String?
    val foo2: String?
    
    mapOf(
       // if (foo1 != null) foo1 to 1 else ???
       // if (foo2 != null) foo2 to 2 else ???
    )
    d
    c
    w
    • 4
    • 3
  • s

    scottiedog45

    04/29/2019, 8:03 PM
    Hi everyone: I’m trying to write a generic function wrapper, but can’t seem to get it quite right. Basically I can’t seem to pass
    LinearLayout
    as an argument here, what’s going on?
    fun <T : View> getView (viewType : T, id: Int) : T {
                return view!!.findViewById<T>(id)
            }
    
            val l = getView(LinearLayout, R.id.settingsLanguageRow)
    r
    • 2
    • 2
  • d

    Dangelomjoyce

    04/29/2019, 10:39 PM
    Good afternoon, I'm new to Kotlin and working through a Big Nerd Ranch book, I came across the function in their code and it isn't working, can someone help me with the solution. val healthStatus = when (healthpoints) { in 100..89 -> EXCELLENT_HEALTH in 90..99 -> GOOD_HEALTH in 75..98 -> MINOR_HEALTH in 75..89 -> if (isBlessed) {IS_BLESSED } else { } in 15..74 -> LOW_HEALTH else -> POOR_HEALTH } ... println("$name $healthStatus") isBlessed is set to true, and I have a string stored in const val IS_BLESSED. The issue I am having is that string is not printing regardless the range of the healthpoints.
    r
    c
    t
    • 4
    • 6
  • a

    aarjav

    05/02/2019, 8:41 PM
    is it possible to get restrict inner class constructor so that only the outer class can instantiate it? Here is the java code that can do it:
    public class Foo {
        public class FooInner {
            public final String key;
            private FooInner(String key) {
                this.key = key;
            }
        }
        public FooInner wrap(String key) {
            return new FooInner( key );
        }
    }
    A hack that may work, but would rather keep constructor public than use: https://stackoverflow.com/a/18634125/5130921
    s
    • 2
    • 1
  • u

    ursus

    05/02/2019, 10:52 PM
    huh
    k
    • 2
    • 1
  • k

    krleg

    05/03/2019, 9:49 AM
    HI, everyone! I am student and just trying to understand kotlin programming language. Is there someone who can help me with app connection to TCP server using IP and port? I need to connect to the server and retrieve data from there. I am ready reading if someone has great material. I never have done this before, so I dont know from where to start.
    d
    n
    • 3
    • 8
  • h

    Hullaballoonatic

    05/05/2019, 8:57 PM
    what would be the underlying difference between
    val self = this
    and
    val self get() = this
    is the latter more expensive for no reason? are they the same?
    d
    k
    • 3
    • 6
  • h

    Hullaballoonatic

    05/06/2019, 7:36 AM
    is there any way to get around
    'public' function exposes 'private' return type
    ?
    d
    • 2
    • 17
  • k

    Kristian

    05/07/2019, 2:13 PM
    The Kotlin koans are very good: https://play.kotlinlang.org/koans/overview
    s
    k
    +2
    • 5
    • 9
  • g

    Goldrichs

    05/08/2019, 4:08 PM
    Hi all, ok downloaded the latest kotlin app on my win 7 computer and it says I need a .yaml document in the directory I created. where do I get said file? And if it is necessary, why isn't it included in the download package?
    👀 2
    k
    • 2
    • 23
  • g

    Goldrichs

    05/08/2019, 7:56 PM
    OK now I'm in the Flutter Console on my win 7 laptop and I'm at the command line. How do I find out what files etc should be in my flutter directory?
    s
    s
    • 3
    • 7
  • g

    Goldrichs

    05/08/2019, 8:03 PM
    Does anyone have a picture of what all the files are that are in the new basic flutter console directory?
    s
    • 2
    • 1
  • c

    crummy

    05/10/2019, 5:08 AM
    Can I override a setter for a constructor
    var
    ?
    o
    t
    m
    • 4
    • 4
  • s

    scottiedog45

    05/10/2019, 10:02 AM
    is there an android studio plugin that will automatically order xml attributes?
    :google: 1
    k
    • 2
    • 1
  • k

    Kumaran Masilamani

    05/10/2019, 7:41 PM
    Can anyone help me to do a pattern match on ADT?
    //Given my ADT as follows ...
    sealed class Result {
        object Success  : Result()
        data class Failure(val reason: FailureReason) : Result()
        enum class FailureReason { REASON1, REASON2 }
    }
    //I want to do something like this
    when (result) {
                is Success -> 
                is Failure(REASON1) -> 
                is Failure(REASON2) -> 
            }
    In Scala I will use with a variable, but it didn't work in Kotlin
    m
    m
    • 3
    • 11
  • h

    Hullaballoonatic

    05/10/2019, 8:43 PM
    is there a list building method that can reference previously constructed elements of the list while building it that i'm not seeing? Or does the collection not exist until after all its elements are determined, so that's not really possible in as a List constructor
    l
    k
    • 3
    • 32
  • k

    karelpeeters

    05/11/2019, 5:54 PM
    It's easy to get lost in the
    <?>
    stuff 😒imple_smile:
    g
    • 2
    • 27
  • l

    Lucas

    05/13/2019, 11:44 AM
    Hi just wondering is there an idiomatic iteration pairwise over a list or array, eg:
    a b c d
    iterated as
    a b; b c; c d
    . This is to calculate the delta between elements
    d
    p
    +2
    • 5
    • 14
  • j

    j_recuerda

    05/13/2019, 2:09 PM
    Hi! I am coming from the C++ world, is there a way to declare an implicit constructor or an implicit casting operator? I mean, I want to publish on my API a function which takes 3 arguments and two of them can come as a Long or as an instance of an object which can be instantiated given a Long. Is there a way to avoid publishing the overloads for all posible combinations?
    🇳🇴 1
    s
    • 2
    • 3
  • a

    Aleks Clark

    05/13/2019, 6:07 PM
    (I get a
    ByteReadChannel
    from ktor)
    d
    m
    • 3
    • 3
  • f

    Florian

    05/14/2019, 1:48 PM
    is there a summary how Kotlin/VM differs from /JS and /Native?
    r
    c
    • 3
    • 14
  • j

    jschneider

    05/15/2019, 1:30 PM
    Hi guys. Need some help with coroutines. I want to achieve something: From one (or many coroutines / threads) something is marked as dirty. Another coroutine waits for that marker and starts a (long running) calculation. I want to have two things: - the calculation should only run at most once per second - I do not care how often the dirty marker is set (probably very often). I just want to calculate once.
    m
    • 2
    • 8
  • j

    jschneider

    05/15/2019, 1:30 PM
    Therefore channels does not seem to be the right thing for me. What should I use instead?
    k
    • 2
    • 1
  • q

    Quinn

    05/15/2019, 1:38 PM
    Having problems with the following code. When I call .sort { a,b -> distanceFormula } I can no longer access the array named sources. If I don't call sort I have no problems.
    var sources = spawn.room.find(FIND_SOURCES).sort { a,b ->
            (a.pos.x - b.pos.x) * (a.pos.x - b.pos.x)
             + (a.pos.y - b.pos.y) * (a.pos.y - b.pos.y)}
        val creepsWithSource1 = creeps.count { it.memory.assignedSource == sources[0].id }
        val creepsWithSource2 = creeps.count { it.memory.assignedSource == sources[1].id }
        val assignedSource = if(creepsWithSource1 < creepsWithSource2) sources[0].id else sources[1].id
    This results in the following error message. I'm trying to decipher what this error means so I can understand it in the future.
    Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
    public inline operator fun <K, V> Record<Int, [ERROR : No type element]?>.get(key: Int): [ERROR : No type element]? defined in starter
    d
    • 2
    • 13
  • h

    Hullaballoonatic

    05/15/2019, 6:19 PM
    i'd like any instance of a class that inherits from
    Bar
    to be able to call
    foo()
    and return its own type
    d
    j
    • 3
    • 10
  • m

    matt tighe

    05/15/2019, 9:21 PM
    when passing objects as parameters to constructors, are those objects kept as references in the class being constructed, or are they released once construction is complete? eg
    class MyClass(instance: MyObject) {
        val prop = instance.myFun()   
    }
    would
    instance
    be released as soon as construction had completed?
    d
    k
    • 3
    • 5
  • c

    crummy

    05/15/2019, 11:14 PM
    Is there a Kotlin-ish way to loop through some integers but be able to control the iterator? E.g. I want to do something like:
    for (i in (0..100)) {
      if (i == 10) i += 10
    }
    s
    • 2
    • 3
  • m

    Mike

    05/16/2019, 12:51 PM
    So one of the kotlin koans is about using safe casts. For example:
    fun eval(expr: Expr): Int =
            when (expr) {
                is Num -> expr.value
                is Sum -> eval(expr.left) + eval(expr.right)
                else -> throw IllegalArgumentException("Unknown expression")
            }
    
    interface Expr
    class Num(val value: Int) : Expr
    class Sum(val left: Expr, val right: Expr) : Expr
    What I don’t understand is the use of the “eval” . If you go look at the kotlin docs they say “don’t use! Really Bad!” And it seems like you would want to do something like expr.left.value + expr.right.value. But it doesn’t know if left and right are Expr or Num. So you should be able to explicitly cast, but then you have to check to make sure it is the right type. It gets very messy very quick. Am I missing something? Or is this really just a made up example and in real-life we’d never do something like this. If I was doing this pattern in real code, I don’t think I’d use the data class / interface this way. I’d be able to get the classes to evaluate down to a value on their own, but then I wouldn’t need to worry about downcasting then (which defeats the point of the exercise)
    t
    k
    m
    • 4
    • 5
  • j

    jaspersmit

    05/16/2019, 1:40 PM
    How can i get an enum value from a string? i only have a kclass, so not the concrete enum class
    d
    h
    s
    • 4
    • 6
Powered by Linen
Title
j

jaspersmit

05/16/2019, 1:40 PM
How can i get an enum value from a string? i only have a kclass, so not the concrete enum class
d

dalexander

05/16/2019, 2:02 PM
I typically write a
fromString(someString: String): YourEnum
function for that kind of behavior. I don't know of a built in
String -> Enum
converter.
h

hho

05/16/2019, 2:15 PM
The built in
String -> Enum
is called
valueOf
(a synthethic method, just like in Java). Example: https://pl.kotl.in/Ucxx-Y8cd
However, for this you need the actual Enum, not just its
KClass
. 🤔
j

jaspersmit

05/16/2019, 2:17 PM
i now use :
val theClass = current.javaClass
                return theClass.enumConstants.first { it.name ==  name }
s

spand

05/16/2019, 2:23 PM
Why dont you just use javas:
java.lang.Enum.valueOf(Foo::class.java, strValue)
j

jaspersmit

05/16/2019, 2:30 PM
right even better
View count: 3