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

    pambrose

    09/10/2019, 8:33 PM
    I have a simple example of using select{} on mutex.onLock: https://gist.github.com/pambrose/4eb82e623161ee7758551ad6a9649ab6 Based on the docs and the name “onLock” I am expecting the select to take place when an unlocked mutex is locked. However, I am seeing the opposite behavior, i.e., if I use locked mutexes, I am seeing the select take place when the mutex is unlocked. The docs for Mutex.onLock say that it “selects when the mutex is locked.” Given the behavior I am seeing, I would expect the name to be “onUnlocked”. I would appreciate someone setting me straight on this.
    e
    6 replies · 2 participants
  • w

    w_bianrytree

    09/11/2019, 8:53 AM
    Hey guys. Is there a way that I can call a method in Java that have a generic boundary? Let’s say my method in Java:
    public static <T extends A&B> void methodA()
    Where A B are different interfaces I can call the method in Java without any type like this:
    methodA()
    But when I call that method in kotlin I don’t know what type I should give to it
    methodA</*What Should I put it here?*/>()
    Any ideas?
    g
    m
    +1
    7 replies · 4 participants
  • x

    XQDD

    09/11/2019, 10:37 AM
    Any idea for abstraction CaptchaType? I do it this way because the annotation parameter only receive const value( compile-time constant )
    Untitled
    m
    15 replies · 2 participants
  • e

    epchris

    09/11/2019, 7:48 PM
    Hi! I just recently started trying to use coroutines (in an app that uses spring boot, fwiw) and I keep getting this error:
    java.lang.ClassNotFoundException: kotlin.coroutines.jvm.internal.SuspendLambda
    I’m using gradle to build the project and have this in place
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1'
    (using old version b/c we’re on kotlin 1.3.20 for now) Any ideas what might be going on?
    l
    2 replies · 2 participants
  • s

    Sam

    09/12/2019, 7:33 AM
    Hello everybody , Do you know any open source application which implement this concept
    finite state machine
    ? I found some libraries implemented this concept but need more information to implementing this .
    <https://github.com/Tinder/StateMachine>
    <https://github.com/open-jumpco/kfsm>
    j
    c
    +1
    17 replies · 4 participants
  • l

    LastExceed

    09/12/2019, 9:02 AM
    i have a mutable list of objects, and a reference to one of the objects in that list. i want to keep every object from start until (including) the object i have a reference to, and drop everything that comes afterwards. I see countless ways to do this (e.g.
    myList.dropLast(myList.size - 1 - myList.indexOf(thatObject))
    ) but none that really satisfies me in terms of readability. can you guys give me some suggestions? I figured the best way would involve
    myList.retainAll()
    somehow but i couldnt find a good way to make use of it
    w
    8 replies · 2 participants
  • m

    Matej Drobnič

    09/12/2019, 10:18 AM
    What is the ideomatic way to perform automatic dependency injection in functional Kotlin code? At the moment, most of my code is very java-like where it contains bunch of classes that contain business logic and dependencies between those classes are resolved with Dagger's constructor injection. Top level functions are mostly used as utility functions. This works fine, but it seems like Kotlin promotes a pattern where code is instead moved from classes into top level functions that cannot have dependencies easily injected (without passing everything manually of course). One practical example is with coroutines. Convention dictates that functions launching new coroutines should be declared as extension functions of
    CoroutineScope
    . This practically requires such functions to reside on top level, since calling member extension functions of other classes is very awkward in Kotlin. But on the other hand, I fail to see how to properly handle dependencies in top level functions. * For example if I have
    Downloader
    class that has
    CoroutineScope.startDownloading
    method, I can inject every dependency of the downloader easily via constructor, but calling
    startDownloading()
    is awkward (I need to call it via
    with (downloader) {startDownloading())
    statement). * On the other hand, if I just create
    CoroutineScope.startDownloading()
    top level method, it would be easy to call, but I would have to provide dependencies with every single call to that method, which would create messy code.
    s
    s
    +2
    10 replies · 5 participants
  • w

    widar

    09/12/2019, 12:49 PM
    Anyone got experience packaging an executable fat jar file with kotlin using gradle? Most resources I have found seem to be pointing toward doing like in this post https://medium.com/@preslavrachev/kotlin-basics-create-executable-kotlin-jars-using-gradle-d17e9a8384b9 But I still get the `NoClassDefFoundError: kotlin/jvm/internal/Intrinsics`even though I've done like that
    b
    t
    +1
    6 replies · 4 participants
  • a

    Andreas Unterweger

    09/12/2019, 1:06 PM
    i created an string extension function like so:
    fun String.resourceContent() : String = javaClass.getResource(this).readText()
    if i call
    "/token.json".resourceContent()
    in the test i get null if i call
    javaClass.getResource("/token.json")
    in the test it works why does this not work in an extension function?
    c
    m
    5 replies · 3 participants
  • h

    hikamaeng

    09/12/2019, 2:54 PM
    Hello~
    infix fun <A, B, C> Pair<A, B>.to(that:C) = Triple(this.first, this.second, that)
    ❓ 3
    r
    j
    4 replies · 3 participants
  • p

    Paul Woitaschek

    09/12/2019, 5:06 PM
    You can still use a factory method in case you need validation. Letting the data class validate it's content makes sense. Like EmailAddress.parse and then make the constructor private. @ursus
    w
    2 replies · 2 participants
  • k

    kevinmost

    09/12/2019, 7:15 PM
    https://pl.kotl.in/zXrGRcejU seems like a weird bug with nullable generics. Try running it, then remove
    reified
    from the function header and run again
    r
    c
    7 replies · 3 participants
  • z

    zachtib

    09/12/2019, 7:41 PM
    @Pablo Schmid are you returning something out of it, or otherwise doing something that requires it to be exhaustive?
    👆 1
    p
    a
    14 replies · 3 participants
  • r

    Roberto Messina

    09/12/2019, 10:55 PM
    Right?
    Untitled
    s
    r
    +1
    18 replies · 4 participants
  • s

    Soren Valle

    09/12/2019, 11:05 PM
    I don't think this is possible without an extra param in
    genericBuilder
    , but I don't know all the things.
    class GenericClass<T> {
        var property: T? = null
    
        fun genericBuilder(builder: T.() -> Unit) {
            // how to initialize T?
            property?.builder()
        }
    }
    r
    e
    7 replies · 3 participants
  • r

    Roberto Messina

    09/13/2019, 12:21 AM
    i wanna do this thing
    a
    2 replies · 2 participants
  • w

    wathek

    09/13/2019, 2:52 PM
    Hi guys, I'm facing a dilemma and I need your advice. Which one of these two lines you think is better:
    val parsedValue = if (propertyValue is String) propertyValue.toDouble() else propertyValue as Double
    VS
    val parsedValue = (propertyValue as? String)?.toDouble() ?: propertyValue as Double
    s
    m
    8 replies · 3 participants
  • m

    Marcin Wiśniewski

    09/13/2019, 3:40 PM
    Hi, is there anybody who are using ktor for REST API and has experience in writing IT tests with mocks? Lets assume that I use a kind of service class in my routing. I need to mock that service and test concrete routing / endpoint
    m
    t
    +1
    4 replies · 4 participants
  • m

    Mohammed Saied Mostafa

    09/13/2019, 4:30 PM
    guys what is the most important thing to do when go to interview as android developer ?!
    o
    l
    9 replies · 3 participants
  • k

    Kroppeb

    09/13/2019, 6:15 PM
    I have some raw bytes (byteChannel / byteArray/byteReadPacket) and want to compress/decompress it (standard DEFLATE). Any sugestions?
    k
    1 reply · 2 participants
  • t

    tipsy

    09/13/2019, 9:53 PM
    i have a line:
    if (header?.startsWith("Basic ") != true) throw Exception
    . intellij is suggesting i replace this with
    require(header?.startsWith("Basic ") == true)
    , but if i do that,
    header
    is no longer smart cast
    w
    k
    4 replies · 3 participants
  • n

    nfrankel

    09/14/2019, 6:01 AM
    i don’t know but sometimes, by listening to what intellij tells you do to the code doesn’t compile anymore
    👍 2
    s
    m
    7 replies · 3 participants
  • y

    yschimke

    09/14/2019, 1:54 PM
    Some thoughts from recent interview processes. Kotlin is the best language for interviews I could imagine. Even people unfamiliar with Kotlin can understand and so many things are trivial to implement.
    n
    m
    +1
    13 replies · 4 participants
  • k

    Kroppeb

    09/15/2019, 10:05 PM
    I'm getting a NPE on this lines? Any ideas how that can happen?
    d
    8 replies · 2 participants
  • a

    andrzej

    09/16/2019, 10:45 AM
    What is the idiomatic way in Kotlin of a doing a "mapping" of one object into another one. e.g. from
    User(firstName: String, lastName: String, age: Int)
    to
    UserEntity(name: String, age: Int)
    . I found that using a scope function is very useful but I don't know which would be the best. The pros and cons are as follows: •
    let
    seems as natural choice since it returns lambda result but having to repeat
    it
    for every property feels a little redundant, e.g.
    user.let { UserEntity(it.firstName + it.lastName, it.age)}
    •
    run
    allows to eliminate
    it
    from the above example but
    run
    looks awkward as a mapping function, e.g.
    user.run { UserEntity(firstName + lastName, age)}
    •
    with
    also seems a viable option, e.g.
    with(user) { UserEntity(firstName + lastName, age)}
    but I'm not sure if this is intended usage of
    with
    function, in Kotlin docs it is described as a function which lambda result should not be returned or as way to introduce a helper object (https://kotlinlang.org/docs/reference/scope-functions.html), so I'm not sure
    w
    s
    +5
    17 replies · 8 participants
  • g

    Gunslingor

    09/16/2019, 12:13 PM
    I've got a small little 24 lines of kotlin code that just queries java to get properties like version. Yet for some reason the jar that gets produced is 35MB in size. At the same time, the actual intelliJ project is only 9KB in size... this cannot be right, I use only native packages no imports, simple code, WTF is going on here?
    package org.ppp.installer
    
    object JavaGetProperty {
        @JvmStatic
        fun main(args: Array<String>) {
            try {
                val property = args.getOrNull(0)
                var propertyVal: String
    
                if (property == "java_patch") {
                    //Custom Properties
                    val fullVersion = System.getProperty("java.version", "unknown")
                    propertyVal = fullVersion.split("_")[1]
                } else {
                    //Direct Unprocessed Properties
                    propertyVal = if (property != null) System.getProperty(property, "unknown") else "unknown"
                }
    
                print(propertyVal.trim())
            } catch (e: Exception) {
                print("unknown")
            }
        }
    }
    t
    12 replies · 2 participants
  • z

    zak.taccardi

    09/16/2019, 3:03 PM
    has anyone heard of a library that provides a delegated property for constructing things in JUnit’s setUp phase automatically? instead of:
    private lateinit var dog: Dog
    
    @Before fun setUp() {
      dog = Dog()
    }
    there would be:
    private val dog by before { Dog() } // constructs `Dog` instance once per test
    w
    s
    +3
    12 replies · 6 participants
  • d

    David Glasser

    09/16/2019, 5:14 PM
    Is it safe to assume that collection transformation functions like
    map
    return Lists whose
    get
    method is O(1)? If so, is that documented?
    s
    c
    24 replies · 3 participants
  • b

    Bruno Garcia

    09/16/2019, 6:45 PM
    Is there a way to instantiate an object while setting some properties on it? As an expression like:
    val a = Some() { b = "value" }
    Or do I need multiple lines for that
    s
    s
    +1
    9 replies · 4 participants
  • s

    scottiedog45

    09/16/2019, 10:40 PM
    Swift has a funtionBuilder/propertyWrapper that’s pretty nifty. Does kotlin have something like this? Something like
    @sumOnlyOddInts
    above a list of ints would filter the ints.
    c
    1 reply · 2 participants
Powered by Linen
Title
s

scottiedog45

09/16/2019, 10:40 PM
Swift has a funtionBuilder/propertyWrapper that’s pretty nifty. Does kotlin have something like this? Something like
@sumOnlyOddInts
above a list of ints would filter the ints.
c

Casey Brooks

09/16/2019, 10:47 PM
I’m not too familiar with Swift, but perhaps property delegates are what you’re looking for? https://kotlinlang.org/docs/reference/delegated-properties.html
👍 1
➕ 1
View count: 5