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

    182630g

    03/18/2020, 2:52 AM
    Hi im trying to build my build my app in Unity but when I click on Build , this appears 😞 anyone knows the solution ? Cant seem to find it
    i
    • 2
    • 6
  • a

    Ajinkya Saswade

    03/18/2020, 3:04 PM
    Just published an article on Jetpack compose. About how it works, why it was introduced, what problems it solves, etc. Please go through it whenever you get time and provide your feedback. Thanks https://medium.com/@ajinkyasaswade09/jetpack-compose-what-problem-does-it-solves-110ed9314dbe
    e
    • 2
    • 2
  • s

    Steve

    03/18/2020, 7:51 PM
    How do I OR together constants in Kotlin?
    c
    p
    • 3
    • 3
  • c

    Czar

    03/19/2020, 6:11 PM
    Hi, does this make sense? I know it's generalizable with comparables, I'm just interested if this simple version can be written better.
    fun Sequence<Int>.isOrderedAscending(): Boolean =
    	zipWithNext { prev, next -> prev <= next }
    		.fold(true) { acc, value -> acc && value }
    s
    t
    • 3
    • 5
  • i

    Ivan Brko

    03/20/2020, 10:06 AM
    Hi all, can anyone reccomend a good site or smaller book or something to get started with kotlin? i have prior programming experience (mostly oop but also hobbyist fp) and I'm looking for something that will help me write some code quickly. i don't want to go through someone explaining me what if/else is and at this point i don't want a book that goes in depth and that would take me a month to read.
    k
    s
    j
    • 4
    • 7
  • g

    gabin

    03/20/2020, 4:53 PM
    Hi Guys. Could you point me a native kotlin class for working with Date?
    j
    • 2
    • 2
  • m

    Michael Saragih

    03/21/2020, 9:22 AM
    hello guys, anyone know which library/framework good for back-end of the web for newbie in kotlin
    a
    d
    j
    • 4
    • 5
  • k

    keochris

    03/21/2020, 9:25 AM
    Hello, I have been coding some Kotlin and ktor programs for some time but I am not a real developer and more importantly, I don’t know Java (at some point, it can be an issue with Kotlin). Then sorry for the following stupid question but if someone can point me out to good doc about those “@” annotations that I find in most advanced codes, it would fantastic! Thank you!
    n
    • 2
    • 4
  • i

    iseki

    03/22/2020, 5:17 AM
    Hello, I have a problem. How to cast type
    <T>
    to
    <Base<T>>
    ?
    open class C<T:C<T>>{
        fun <R> foo(a:R){
            a as T // looks not works...
        }
    }
    t
    • 2
    • 2
  • r

    Ray Ryan

    03/23/2020, 8:42 PM
    I’m probably asking this in the wrong channel, but I’m not sure what the right one is. The question is, how do you extend an abstract inner class in Kotlin? This is legal Java:
    class Outer {
      abstract class Inner {
      }
    }
    class Child extends Outer.Inner {
      Child(Outer outer) {
        // Calls Inner constructor, providing
        // outer as the containing instance
        outer.super();
      }
    }
    I can’t find an equivalent in Kotlin, if I want
    Child
    to live in a separate file / module. The auto converter generates this, which doesn’t compile:
    class Outer {
      abstract inner class Inner
    }
    
    class Child(outer: Outer?) : Inner()
    🤯 2
    c
    b
    • 3
    • 8
  • z

    zero_coding

    03/24/2020, 1:29 PM
    Does it exists immutable list in Kotlin?
    d
    m
    s
    • 4
    • 9
  • g

    Gilberto Diaz

    03/24/2020, 2:43 PM
    What’s the correct name when you create a
    fun Int.add(){}
    . I’m trying to find docs about this approach but can’t find it.
    m
    • 2
    • 8
  • v

    Victor Cardona

    03/24/2020, 10:45 PM
    What is the most idiomatic way of expressing a class hierarchy in Kotlin? I found this blog post which used delegation, but I have heard that delegation is not a feature that many developers choose to use. Though in this case I can’t see the downside to it. My specific use case is a set of immutable classes where sub classes add additional properties only. Thanks!
    d
    • 2
    • 4
  • g

    Gus

    03/26/2020, 4:24 PM
    I need to create 4 subclasses of an abstract class whose sole constructor has 7 parameters (3 of which are required). Is there a way to avoid having to replicate the parent class' contructor signature so many times?
    s
    a
    • 3
    • 6
  • o

    oday

    03/30/2020, 2:51 PM
    how can I find an item in a list according to an ID that I have, and then replace the item there with the object i have (whose ID i used to find its occurrence in the list)?
    a
    • 2
    • 7
  • g

    Gus

    03/30/2020, 5:03 PM
    Hi. If I have a sub-class that sets a different companion object from its parent class, can a method on the parent class access the companion object of the current sub-class? Here's some code:
    open class TheCompanion(val foo: String)
    
    open class Parent {
        fun doIt(): String {
            return foo
        }
    
        companion object : TheCompanion("the-parent")
    }
    
    class Child1() : Parent() {}
    
    class Child2() : Parent() {
        companion object : TheCompanion("child2")
    }
    
    Child1().doIt()
    Child2().doIt()
    How can I get
    Child2().doIt()
    to output
    "child2"
    instead of
    "the-parent"
    ? I guess this isn't possible because there's no way to enforce that subclasses of
    Parent
    must have a companion object implementing a given interface, right?
    s
    • 2
    • 4
  • g

    Giovanni Attina

    04/01/2020, 1:27 AM
    Hi! I'm learning Kotlin, I came from Javascript/Python and I'm focusing now in Kotlin in JVM to backend development. And now at my learning path, I'm learning how to create tests for my projects, should I start to learn JUnit or Spek? Both frameworks are very different. I appreciate Speak, using BDD, but I'm facing a little difficult to setup with IntelliJ. JUnit has a bigger community and the resources to learn look much better. What are you guys are using? Which one do you prefer? PS: I learn Kotlin because I'm moving to a new company and the squad I'm going to work use Kotlin.
    d
    p
    +3
    • 6
    • 6
  • i

    Ivan Brko

    04/01/2020, 11:15 AM
    Hi all, I'm learning Kotlin through koans and I saw this code (not my, part of the exercise). The code is here: https://pastebin.com/A7vwUqiy I don't understand why the extension method set (at the bottom of the snippet) was written as an extension method? why not just write it as a normal method inside the Tag class? Is this just more idiomatic in Kotlin, or do you achieve something here that cannot be achieved with normal methods?
    d
    r
    • 3
    • 4
  • o

    oday

    04/01/2020, 1:59 PM
    private fun getActiveFilters(categoryId: Int): String? {
            val activeFilters =  mutableFilterItems.value?.mapNotNull {
                it.takeIf { filterItem ->
                    filterItem.categoryId == categoryId && filterItem.toggled
                }
            }?.joinToString { it.itemValue.capitalize() }
            
            return activeFilters
        }
    s
    s
    • 3
    • 4
  • o

    oday

    04/01/2020, 1:59 PM
    if
    activeFilters
    is null or empty, I want to return null, otherwise I want to return activeFilters
    h
    • 2
    • 1
  • o

    oday

    04/01/2020, 1:59 PM
    how do I kotlinize that
    l
    t
    • 3
    • 2
  • h

    harry.singh

    04/07/2020, 10:52 PM
    Is return type of
    plusAssign
    operator function always
    Unit
    ?
    :yes: 1
    t
    • 2
    • 1
  • b

    Ben

    04/08/2020, 10:54 AM
    I have some code that in Java I'd write
    if (getFoo() != null && barEnabled()) {
        doSomething();
    }
    In Kotlin I could write
    getFoo().takeIf { barEnabled() }?.let { doSomething() }
    but I'm not convinced that's any easier to read, mostly because of the separation between the nullable getFoo() and the let. Any recommendations on how best to write that in Kotlin? Is using scope functions always preferred?
    d
    j
    • 3
    • 3
  • u

    ursus

    04/09/2020, 3:26 AM
    can there something be done about it? its annoying me in the new kotlin, although I see its point
    e
    • 2
    • 1
  • u

    ursus

    04/09/2020, 3:28 AM
    I mean I really likes the smart casts, this feels like a step back
    s
    d
    k
    • 4
    • 27
  • v

    vinny2020

    04/09/2020, 6:40 PM
    Hello All, old javahead here, is there a more elegant way in deal with the classic issue of having to double iterate data struictures like : List<MyPojo> when MyPojo also has collection as a property (ex var myProp: List<String> ) ?
    c
    • 2
    • 4
  • i

    Ilya Pogrebenko

    04/10/2020, 8:37 AM
    Hi all. How can I get value of const property of object with reflection?
    object Consts {
        const val KOTLIN = "kotlin"
    }
    Consts::class.memberProperties.forEach { println(it.get(???)) }
    What should I pass as a receiver?
    • 1
    • 1
  • a

    Ananiya

    04/11/2020, 5:34 AM
    What is the difference between object and class And what is const
    s
    • 2
    • 1
  • a

    Ananiya

    04/11/2020, 11:33 AM
    how to make windows app using kotlin
    :google: 4
    r
    • 2
    • 2
  • c

    Chris Cordero

    04/11/2020, 9:37 PM
    I've got a
    List<Int>
    that I want to map over and do some calculations on. Since I'm learning Kotlin, I thought I'd try to do it two ways. This one works:
    val foo: List<Int> = listOf(100, 200, 300)
    foo.map { it / 3 - 2 } .forEach { println(it) }
    However, I wanted to see what to do if I wanted to make a reusable transform function inside the
    map
    . So I tried this:
    fun myMapFunc(it: Int): Int {
        return it / 3 - 2
    }
    
    val foo: List<Int> = listOf(100, 200, 300)
    foo.map(myMapFunc).forEach { println(it) } // error
    I already know I can fix it by doing this:
    foo.map { myMapFunc(it) }
    But I feel like the first way should work too... Why doesn't it?
    s
    • 2
    • 16
Powered by Linen
Title
c

Chris Cordero

04/11/2020, 9:37 PM
I've got a
List<Int>
that I want to map over and do some calculations on. Since I'm learning Kotlin, I thought I'd try to do it two ways. This one works:
val foo: List<Int> = listOf(100, 200, 300)
foo.map { it / 3 - 2 } .forEach { println(it) }
However, I wanted to see what to do if I wanted to make a reusable transform function inside the
map
. So I tried this:
fun myMapFunc(it: Int): Int {
    return it / 3 - 2
}

val foo: List<Int> = listOf(100, 200, 300)
foo.map(myMapFunc).forEach { println(it) } // error
I already know I can fix it by doing this:
foo.map { myMapFunc(it) }
But I feel like the first way should work too... Why doesn't it?
s

Shawn

04/11/2020, 9:49 PM
it’s because unlike python and similar other languages, function references must be deliberately qualified in order to be passed as an argument or assigned to a variable
try
foo.map(::myMapFunc)
c

Chris Cordero

04/11/2020, 9:50 PM
That works
Some follow up questions: 1. What do you mean by "deliberately qualified"? 2. What is the
::
doing?
I can see here: https://kotlinlang.org/docs/reference/keyword-reference.html#operators-and-special-symbols That the
::
means that it is "creating a member reference or class reference", but I'm not sure what that means here exactly.
s

Shawn

04/11/2020, 9:55 PM
So the way symbols work in Kotlin is kinda sorta similar to how it’s done in Java, which doesn’t treat methods or classes as first-class tokens
if you want to pass in data about a class’s type to a function, you can’t just use the class’s name, like
foo(Bar)
you can pass in
foo(Bar::class)
which will generate a
KClass<Bar>
for you and send that to the function
i.e. a class reference
this isn’t just to mirror how Java does things — using a class name without
::
will actually let you reference a class’s
companion object
if one is defined on it
as for the member reference bit, technically speaking, Kotlin allows you to represent a reference to any member of a given class (or top-level declarations in a Kotlin file, which technically compiles to a class on the JVM anyhow)
references to variables aren’t supported yet, but you can reference method/functions as well as properties (variables that are class members and have accessors generated for them) just fine (you really should just have a read of this whole page https://kotlinlang.org/docs/reference/reflection.html)
in a very loose, imperfect sense
::
is kinda like using
*
to get a pointer to something in C/C++
(this also has some implications for representing references to constructors but I won’t go down that path unless you ask lol)
c

Chris Cordero

04/11/2020, 10:04 PM
lol that was a great explanation thank you very much for the detailed answer
👍 2
No worries on the constructor thing, I’ve got enough to let marinade in my head
👌 1
View count: 3