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

    camkadev

    11/02/2018, 5:24 AM
    i think this extension function should be part of Kotlin fun <T> List<T>.exists(predicate: (T) -> Boolean): Boolean { return this.firstOrNull(predicate) != null } to do things like this someList.filterNot { p -> anotherList.exists { e -> e.anotherId == t.someId } }
    g
    r
    • 3
    • 12
  • g

    gildor

    11/02/2018, 9:22 AM
    anywhere where I don’t have params or I have the same same set of params for all items and do not expect that this set will be changed Also if I want to iterate all available values of Enum
    👍 1
    j
    • 2
    • 1
  • c

    ckchen

    11/02/2018, 9:37 AM
    “Each enum constant is an object.” I use this to decide if I need an Enum or sealed class.
    👍 2
    g
    • 2
    • 1
  • f

    Fredrik Larsen

    11/02/2018, 9:38 AM
    Any news on multi catch in kotlin?
    g
    • 2
    • 2
  • b

    Barend

    11/02/2018, 9:40 AM
    Why does
    GlobalScope.launch(Dispatchers.Main)
    throw a
    Fatal Exception: android.os.NetworkOnMainThreadException
    and
    GlobalScope.async
    doesn't?
    j
    g
    • 3
    • 16
  • n

    Nikky

    11/02/2018, 9:58 AM
    has anybody tried inine classes with enums yet ? seems to me that would fix
    Each Enum constant is an object
    k
    g
    • 3
    • 10
  • j

    Jakub

    11/02/2018, 10:41 AM
    Cool, how do you organize these functions @karelpeeters? Are they functions kept in data classes, extensions or they are separated Translators or something?
    k
    • 2
    • 2
  • s

    samir

    11/02/2018, 11:07 AM
    Should the second snippet not give a compiler error?
    val imap = mapOf("a" to "a")
    // val mmap = imap as MutableMap
    
        imap["b"] = "b" //compiler error
    val imap = mapOf("a" to "a")
        val mmap = imap as MutableMap
    
        imap["b"] = "b" //runtime error java.lang.UnsupportedOperationException
    d
    e
    +4
    • 7
    • 80
  • o

    orestisfou

    11/02/2018, 12:01 PM
    hello, is it possible to wrap on a sealed class classes of external libs?
    g
    r
    • 3
    • 8
  • y

    yen

    11/02/2018, 12:27 PM
    What’s the best JVM memory profiler out there?
    e
    s
    • 3
    • 2
  • b

    bod

    11/02/2018, 1:53 PM
    I've removed Kotlin dependencies from my project (so I transitively depend from the plugin sdk one) and I no longer have the issue . . . . .
    l
    • 2
    • 3
  • s

    spand

    11/02/2018, 2:54 PM
    In Gradle I can add java-library plugin and get access to the
    api
    method for the dependencies block. Is there a kotlin verion of this ? (do I need one ?)
    g
    • 2
    • 1
  • p

    Paul Woitaschek

    11/02/2018, 3:44 PM
    I am using kotlin for several years now and my programming style is evolving and becoming more functional. I write way more top level functions that I did one year ago. What I ask myself is: What do I do when my functions need more dependencies? Lets say I have a file with one public top level function and it calls private functions which themselfes call other functions too. When I now need the class X and Y in
    fun d(x : X, y : Y)
    it's painful to change all that code just for passing them through from
    fun a(x : X, y : Y)
    ->
    fun b(x : X, y : Y)
    ->
    fun c(x : X, y : Y)
    ->
    fun d(x : X, y : Y)
    . Are there any common approaches / patterns to solve this?
    s
    d
    e
    • 4
    • 5
  • p

    Paul Woitaschek

    11/02/2018, 3:56 PM
    So a realistic example:
    purchaseCardContents
    calls
    purchaseCardContents
    which calls
    toPurchaseCardContent
    several times. Now I need a class
    FormatSavings
    in the last function
    toPurchaseCardContent
    . How do I get it there? When using a class for the whole logic, I just inject it through the constructor. The issue here is that
    toPurchaseCardContent
    doesn't know anything about
    purchaseCardContents
    so I would need to pass-through that class and everything else it needs. Maybe the better question is: How do I get / pass dependencies I don't want the caller to bother about in functional programming?
    Untitled.kt
    l
    • 2
    • 2
  • m

    marcelo

    11/02/2018, 4:29 PM
    Clearly, I am new to
    coroutines
    . Don't know why this code
    experienceTimer.tagVal("/sdsd/login").time {
      Thread.sleep(2)
    }
    unless I have
    suspend {
      experienceTimer.tagVal("/sdsd/login").time {
        Thread.sleep(2)
      }
    }
    Don't think I am doing this right. I feel like the show Pimp My Ride,
    Yo dawg, I heard you like
    suspend
    so I am adding a
    suspend
    and a block of
    suspend
    within the method that I want to
    suspend
    .
    Timer.kt
    k
    r
    • 3
    • 6
  • n

    nickheitz

    11/03/2018, 9:28 AM
    I'm hoping someone here can/will help, as my experience at discuss.kotlinlang.org had been one of unresponsiveness. I believe there is a bug in coroutines when combined with a class using @JvmSuppressWilcards. The description and example is here: https://discuss.kotlinlang.org/t/kotlin-1-3-and-coroutines/10084/4 This had only appears since Kotlin 1.3 and coroutines 1.0.0. should I just be raising this directly as a bug?
    l
    p
    • 3
    • 2
  • h

    hudsonb

    11/03/2018, 12:19 PM
    In the following code, inspections warn about the redundant
    ->
    in the
    else
    of the `when`:
    internal fun hue(a: Double, b: Double): (Double) -> Double {
        val d = b - a
        return when {
            d.isTruthy() -> linear(a, if (d > 180 || d < -180) d - 360.0 * Math.round(d / 360.0) else d)
            else -> { _ -> if(a.isNaN()) b else a } // Redundant lambda arrow
        }
    }
    Removing it changes the type from
    (Double) -> Double
    to
    Double
    . Is there a better approach?
    k
    e
    +2
    • 5
    • 6
  • h

    Hunter Breathat

    11/03/2018, 4:15 PM
    Hey so I'm having issues with setting up kotlin native via Intellij Ultimate
    p
    a
    o
    • 4
    • 7
  • k

    kingsley

    11/03/2018, 4:35 PM
    Following an earlier comment on this channel, using this Gradle Kotlin DSL to enable language flags seem to be working fine. However, there’s no documentation or a mention of it anywhere, regarding whether/not it’s a stable API that should/not be used. I’m curious if this is indeed a recommended solution
    subprojects {
        afterEvaluate {
            the<KotlinProjectExtension>().sourceSets.all {
                languageSettings(closureOf<LanguageSettingsBuilder> {
                    progressiveMode = true
                    enableLanguageFeature("NewInference")
                    enableLanguageFeature("InlineClasses")
                    ...
    
                    useExperimentalAnnotation("kotlin.ExperimentalUnsignedTypes")
                })
            }
        }
    }
    d
    • 2
    • 10
  • e

    edwinRNDR

    11/03/2018, 6:05 PM
    I have recently been running into some (nitpicky?) problems with the typesafe builder pattern. It is the problem where functions inside the builder and outside the builder have similar names but different signatures (but it also happens for functions that have similar names) and users are easily tricked into the wrong function. I have been playing with shadowing those functions inside the builder to prevent users from using the wrong functions, but I can't say it is elegant: https://gist.github.com/edwinRNDR/18bacaf0fc51b44349c748eecbe76dde . What are nicer ways to deal with this problem?
    d
    • 2
    • 1
  • t

    Tolriq

    11/03/2018, 7:03 PM
    Got a quick question about using a Java API from Kotlin. The API in question is the Cast API from Google that is defined in a strange way.
    public final class Cast {
    public static final Cast.CastApi CastApi;
    
        private Cast() {
        }
    
        public interface CastApi {
       }
    }
    Accessing the static final field from Kotlin seems impossible AS always think I'm referring to the interface and not the field, is there any trick for that?
    e
    • 2
    • 5
  • b

    Benoit Duffez

    11/03/2018, 9:15 PM
    fun foo(bar: Long) { ... }
    //elsewhere:
    fun whatever(baz: Long?) = return when {
      baz ?: 0 > 0 -> foo(baz) // here
      else -> null
    }
    why is there no smart cast for baz being non null here?
    k
    h
    k
    • 4
    • 9
  • a

    APXEOLOG

    11/03/2018, 10:04 PM
    return behaviors
                    .map { it to it.getFullUpdate() }
                    .filter { it.second != null }
                    .map { it.second.doSmth(it.first) } // Still nullable
    getFullUpdate()
    can return null, any way i can smart cast
    it.second
    to non-null?
    r
    • 2
    • 1
  • k

    karelpeeters

    11/03/2018, 10:53 PM
    .mapNotNull { it.second }.map{ it.doSmth(it.first) }
    a
    m
    • 3
    • 2
  • h

    Hexa

    11/04/2018, 11:08 AM
    does anyone know why would this result to
    undefine
    when I'm expecting it should be either
    true
    or
    false
    ?
    obj shouldBe instanceOf(SomeClass::class)
    k
    • 2
    • 7
  • m

    Mahdi Javaheri

    11/04/2018, 1:29 PM
    can anyone explain this snippet to me? im confused what exactly happens
    -.kt
    k
    k
    • 3
    • 7
  • m

    Mahdi Javaheri

    11/04/2018, 2:13 PM
    can i use extension functions in polymorphic world? as i tested they are being resolved statically (at compile time)
    open class AquariumPlant(val color: String)
    class GreenLeafyPlant(size: Int): AquariumPlant("Green")
    
    fun AquariumPlant.print() = println("AquariumPlant")
    fun GreenLeafyPlant.print() = println("GreenLeafyPlant")
    
    fun staticExample() {
        val plant = GreenLeafyPlant(size = 50)
        plant.print() // this print's GreenLeafyPlant
    
        val aquariumPlant: AquariumPlant = plant
        aquariumPlant.print() // this print's AquariumPlant !! but in polymorphism should be GreenLeafyPlant
    }
    is there a way to bypass this and benefit from Polymorphism
    p
    • 2
    • 1
  • n

    Nikky

    11/04/2018, 2:16 PM
    i do tis by making the class generic
    Plant<PlantType>
    m
    • 2
    • 1
  • h

    Hexa

    11/04/2018, 3:45 PM
    does it make sense to mark a function/method as
    internal
    so that it can be unit tested? or is there a better way to do it without marking it as internal or public?
    s
    m
    +2
    • 5
    • 7
  • m

    mzgreen

    11/05/2018, 7:50 AM
    What is a cleaner way to do this:
    var foo: String = "foo" // set is not invoked during initialization
        set(value) {
            print("SET $value")
            field = value
        }
    
    init {
        foo = "foo" // have to do this in order to invoke set function
    }
    property with custom setter can’t be
    lateinit
    h
    • 2
    • 3
Powered by Linen
Title
m

mzgreen

11/05/2018, 7:50 AM
What is a cleaner way to do this:
var foo: String = "foo" // set is not invoked during initialization
    set(value) {
        print("SET $value")
        field = value
    }

init {
    foo = "foo" // have to do this in order to invoke set function
}
property with custom setter can’t be
lateinit
h

Hamza

11/05/2018, 7:52 AM
var foo: String by Delegates.observable("foo") {
        prop, old, new ->
        println("$old -> $new")
    }
}
👍 3
u can also create your own delegation, as i dont think that runs on init
m

mzgreen

11/05/2018, 7:55 AM
Didn’t think about property delegates, thanks!
View count: 2