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

    rook

    04/30/2019, 2:45 PM
    Is there a way to infer that the class implementing an abstract class is the caller of a lambda with receiver?
    abstract class AbstractFoo<T> {
      operator fun invoke(action: T.() ->Unit) {
        action() // <-- error here: No value passed for parameter 'p1'
      }
    }
    s
    • 2
    • 2
  • l

    LeoColman

    04/30/2019, 3:27 PM
    Is it possible to do something based on a reified T parameter being another something? I wanted something like
    inline fun <reified T> foo() {
        when(T) {
           is Foo -> tFoo()
            is Bar -> tBar()
        }
    }
    s
    c
    +2
    • 5
    • 22
  • k

    kevinherron

    04/30/2019, 4:55 PM
    anybody have experience using the experimental unsigned types? any words of caution before I move forward with a new project that I plan to use them in?
    b
    j
    • 3
    • 5
  • r

    r2vq

    04/30/2019, 6:23 PM
    I accidentally stumbled on this the other day. If my parameter is defined as a function that takes 3 parameters:
    class MyClass(private val getString: (Context, Int, Array<String>) -> String)
    I can call it with a lambda as such:
    MyClass { context, resId, formatArgs -> context.getString(resId, formatArgs) }
    But I can also use a method reference for the first parameter and if the signature matches the second and third parameter.
    MyClass(Context::getString)
    This is really cool. Is there a specific page on the docs where I can read more about this? I would love to learn more but my :google:-fu is failing me on this topic.
    j
    f
    • 3
    • 3
  • x

    xenoterracide

    04/30/2019, 6:50 PM
    site = <http://dto.site|dto.site> ?: <http://this.site|this.site>!!
    is this the best way to say use first if not null else use second if that also is null thow?
    k
    s
    +3
    • 6
    • 9
  • n

    Nezteb

    04/30/2019, 9:35 PM
    Is there a proposal out there somewhere for Kotlin to support variadic generic type parameters?
    s
    s
    • 3
    • 11
  • n

    Nezteb

    05/01/2019, 1:00 AM
    Are there any tools like Findbugs/Spotbugs/Sonarlint that work for Kotlin? Or do those 3 also work for Kotlin?
    m
    x
    • 3
    • 7
  • y

    Yossi Saiada

    05/01/2019, 11:50 AM
    Is there any simpler way to write it:
    if (y) x.getSomething() else null
    Note that
    x.getSomething().takeIf { y }
    isn't identical, because it always calculate
    x.getSomething()
    .
    🇳🇴 2
    t
    w
    +2
    • 5
    • 4
  • d

    Don Phillips

    05/01/2019, 6:17 PM
    Reading the docs on Ktor's HttpClient and WebSockets - https://ktor.io/clients/websockets.html Am I reading this right that if I use websockets on my server side, I won't be able to use the HttpClient in my clients on any platform other than JVM/Android, as the engine backing it for iOS/JS doesn't support it yet?
    r
    • 2
    • 2
  • k

    Kirill Zhukov

    05/01/2019, 8:01 PM
    Found this ticket but wonder if there’s any other way to achieve the same result? https://youtrack.jetbrains.com/issue/KT-28298
    s
    • 2
    • 11
  • x

    xenoterracide

    05/01/2019, 9:02 PM
    is it possible to have the spots where I have FOLEY_NEW populated via the results of value on the new annotation?
    @Target(AnnotationTarget.FUNCTION)
    @Retention
    @RabbitListener(
        bindings = [QueueBinding(
            key = [Amqp.FOLEY_NEW],
            value = Queue(Amqp.FOLEY_NEW),
            exchange = Exchange(name = "amq.topic", type = ExchangeTypes.TOPIC  )
        )]
    )
    annotation class Listener( val value: String )
    k
    • 2
    • 1
  • a

    Andrew Gazelka

    05/01/2019, 10:52 PM
    how do you suggest me making a custom IO dispatcher? (there will be a loop on the main thread which updates coroutines every 20 ms)
    g
    • 2
    • 5
  • h

    Hullaballoonatic

    05/02/2019, 1:43 AM
    How expensive is
    MutableList::toList
    ? Is it just basically a toggle or something, or does it have to copy values into a new object? I imagine that perhaps mutable list is a wrapper for list, but i'm not sure
    g
    m
    +2
    • 5
    • 9
  • h

    Hullaballoonatic

    05/02/2019, 4:40 AM
    How reliable is comparing Doubles? Should I create a safe compare function with some small wiggle room? like
    fun Double.equals(b: Double): Boolean = abs(this - b) < 1e-20
    ?
    s
    k
    s
    • 4
    • 4
  • g

    Geert

    05/02/2019, 8:28 AM
    Well I opened a issue on GSON. It does not serialize my objects correctly: https://github.com/google/gson/issues/1524
    j
    m
    • 3
    • 2
  • b

    Bernhard

    05/02/2019, 10:07 AM
    Hi, I was wondering how you test functions that are private to a file? If you make it private you don't have access to it of course but public doesn't make sense since it's only used in that file
    j
    t
    +2
    • 5
    • 20
  • r

    ribesg

    05/02/2019, 10:15 AM
    Is there a built-in delegate builder to delegate a property to another one?
    private class A {
        var x: Int
    }
    private val a = A()
    var x: Int by a.x // Something like that
    y
    • 2
    • 4
  • c

    carlos cdmp

    05/02/2019, 11:12 AM
    I usually use Objects to isolate functionality, like
    object TextUtils
    for instance, instead of just top level functions, as it is creating an instance, it should be using more memory than an old java static function. Do someone know if an object with only functions its a waste of memory when the functions could be top-level?
    d
    r
    • 3
    • 2
  • d

    Dias

    05/02/2019, 11:29 AM
    I wonder is there is anything wrong conceptually with using interface with default methods as opposed to using an abstract class, given that I don't care about constructors and states?
    r
    a
    • 3
    • 6
  • b

    Bernhard

    05/02/2019, 12:49 PM
    is there a neat way to group by value and respect adjacency? e.g. ["aa", "aa", "a", "aa"].adjacentGroupBy(String::length) should return [["aa", "aa"], ["a"], ["aa"]]
    t
    h
    +2
    • 5
    • 19
  • g

    gustavo.ross

    05/02/2019, 12:57 PM
    Anyone here have built an iOS App using Kotlin Native, and can tell how was this experience?
    d
    d
    +2
    • 5
    • 8
  • s

    Stephan Schroeder

    05/02/2019, 2:23 PM
    Kotlin confuses which Spring method to call:
    <T> T getBean(String name, Class<T> requiredType) throws BeansException;
    	Object getBean(String name, Object... args) throws BeansException;
    I want to call the former, but Kotlin calls the later and then flags my implementation as not guaranteeing the specified type
    fun worker(worker: String): PipelineElementProcessor = try {
        context.getBean(worker, PipelineElementProcessor::javaClass)
    }
    Is there as solution apart from casting the result to PipelineElementProcessor?
    r
    l
    o
    • 4
    • 14
  • s

    Stephan Schroeder

    05/02/2019, 3:11 PM
    I thought that Spring5 was completely annotated with nullibility information but e.g. the methods in BeanFactory like
    /** ...
    	 * @param name the name of the bean to retrieve
    	 * @return an instance of the bean
    	 * @throws NoSuchBeanDefinitionException if there is no bean with the specified name
    	 * @throws BeansException if the bean could not be obtained
    	 */
    	Object getBean(String name) throws BeansException;
    doesn’t seem to be?! (code from spring-beans-5.1.5.RELEASE)
    h
    • 2
    • 3
  • h

    Hullaballoonatic

    05/02/2019, 7:25 PM
    i can see why it might not exist because it could be conflated with
    subList
    since they both take two `Int`s as params.
    r
    • 2
    • 11
  • e

    earroyoron

    05/03/2019, 7:27 AM
    ADT, enums vs sealed classes I am arguing with a collegue about using an
    enum
    or
    sealed
    . The scenario is I have implemented an enum and he is asking me to change to sealed, in the first wave of this discussion I was saying that instead of having a thing like:
    sealed class Days {
        object Monday: Days(),
        object Tuesday: Days(),...
    is better to use just an enum He almost has convinced me when he complains about using
    when
    because with enum you have one type.. Thinking about ADTs in our application now I think the sealed class is the right way, it does matter all elements are `object`(singletons) in it. What’s your opinion?
    a
    a
    +4
    • 7
    • 7
  • s

    Stephan Schroeder

    05/03/2019, 12:57 PM
    why can I override String.toUpperCase() but not String.toString() via an extension function?? I’m not surprised that I get a warning that my toString-extension is shadowed, but why isn’t that the case with toUpperCase? https://pl.kotl.in/Fqwewe9CL
    fun main() {
        val result: String = "xY"
        println("${result.toUpperCase()}-${result.toString()}")
    }
    
    fun String.toUpperCase() = "overridde_toUpperCase"
    fun String.toString() = "overridde_toString"
    leads to output
    overridde_toUpperCase-xY
    p
    r
    +3
    • 6
    • 19
  • t

    Thomas

    05/03/2019, 2:40 PM
    Happy Friday all. I'm having trouble with a
    operator fun invoke
    that takes a
    vararg
    . Here's my stripped-down sample code, the trouble is with the syntax
    { fn }
    in
    main
    , it says "Too many arguments for public constructor NamesBuilder() defined in NamesBuilder". :
    class NamesBuilder {
        private val names:MutableList<String> = ArrayList()
        
        fun build(): List<String> = names.toList()
    
        operator fun invoke(vararg data: () -> String): NamesBuilder = this.apply { data.forEach { names.add(it()) } }
    
        companion object Helper {
            operator fun invoke(vararg data: () -> String): List<String> = NamesBuilder()(*data).build()
        }
    }
    
    fun main() {
        val fn: () -> String = { "1" }
        println(NamesBuilder {fn}) // does not work -- Too many arguments...
        println(NamesBuilder.invoke(fn)) // works fine, prints [1]
    }
    As I understand it, the
    { fn }
    syntax should invoke the companion operator fun invoke function... and this works fine if I use
    .invoke(fn)
    . I've tried numerous variations on this theme but no joy. Can someone help me make this work?
    s
    t
    +2
    • 5
    • 10
  • h

    Hullaballoonatic

    05/03/2019, 11:56 PM
    can i overload
    Double::div
    ? i'd like for it to return
    0.0
    when dividing by
    0.0
    in this scope
    n
    k
    • 3
    • 7
  • h

    Hullaballoonatic

    05/04/2019, 3:01 AM
    I've been writing a comprehensive
    Matrix
    class. It extends
    MutableList<Vector>
    (
    Vector
    extends
    MutableList<Double>
    ). This allows me to add really nice and intuitive operator functions for row operations like
    val A = Matrix(5, 5) { i, j -> 1 }
    A.row(2) *= 3
    A[0] += Vector(0.0, 1.0, 3.0, 4.0, 5.0)
    println(A[2]) // < 3.0, 3.0, 3.0, 3.0, 3.0 >
    However, column operations aren't going to work the same way because the row and col getters are as so:
    fun row(i: Int) = this[i]
    fun col(j: Int) = Vector(numRows) { this[it][j] }
    so a row operation is performed on the stored Vector from the MutableList, while the col operation is performed on a newly created Vector that wraps the corresponding values. Does anyone have any ideas how I could allow for col operations in the same intuitive way?
    k
    • 2
    • 121
  • h

    Hullaballoonatic

    05/04/2019, 3:12 AM
    Second, I added some index range setters and getters like this, and I'd like any opinions or concerns with them: whether or not they are appropriate or confusing or anything. examples:
    operator fun get(rowIndices: IntRange, j: Int) = col(j)[rowIndices]
    print(A[1..3, 0]) //  < 1.0, 3.0, 1.0 >
    
    operator fun set(i: Int, colIndices: IntRange, values: List<Double>) {
        for (j in colIndices) this[i,j] = values[j]
    }
    A[2, 0..4] /= 2.0
    print(A[2]) // < 1.5, 1.5, 1.5, 3.0, 3.0 >
    
    operator fun set(rowIndices: IntRange, colIndices: IntRange, op: (Int, Int) -> Double) {
        for (i in rowIndices)
            for (j in colIndices)
                this[i,j] = op(i, j)
    }
    A[1..2, 3..4] = { 0.0 }
    You get the picture. They make me REALLY wish Kotlin allowed for rangeTo operators such as
    ..3
    and
    4..
    that I could bound in the function or supply default arguments into the missing number since it ruins the prettiness of these Range getters/setters to do stuff like
    A[3..lastRowIndex, 2]
    or
    A[5, 2 until n]
    • 1
    • 1
Powered by Linen
Title
h

Hullaballoonatic

05/04/2019, 3:12 AM
Second, I added some index range setters and getters like this, and I'd like any opinions or concerns with them: whether or not they are appropriate or confusing or anything. examples:
operator fun get(rowIndices: IntRange, j: Int) = col(j)[rowIndices]
print(A[1..3, 0]) //  < 1.0, 3.0, 1.0 >

operator fun set(i: Int, colIndices: IntRange, values: List<Double>) {
    for (j in colIndices) this[i,j] = values[j]
}
A[2, 0..4] /= 2.0
print(A[2]) // < 1.5, 1.5, 1.5, 3.0, 3.0 >

operator fun set(rowIndices: IntRange, colIndices: IntRange, op: (Int, Int) -> Double) {
    for (i in rowIndices)
        for (j in colIndices)
            this[i,j] = op(i, j)
}
A[1..2, 3..4] = { 0.0 }
You get the picture. They make me REALLY wish Kotlin allowed for rangeTo operators such as
..3
and
4..
that I could bound in the function or supply default arguments into the missing number since it ruins the prettiness of these Range getters/setters to do stuff like
A[3..lastRowIndex, 2]
or
A[5, 2 until n]
In the meantime i just made a
til
infix to be short for
until
, even though it is far worse 😮
View count: 3