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
stdlib
  • m

    Mark

    04/30/2019, 11:53 AM
    Curious why
    emptyList()
    is a
    fun
    and not a
    val
    ? I can only guess it’s to do with generics
    :yes: 2
    i
    • 2
    • 2
  • m

    Marc Knaup

    05/08/2019, 12:46 PM
    I'd love to see half-open ranges in Kotlin just like in Swift! Is there a reason there are none (yet)? Something along these lines: https://github.com/fluidsonic/fluid-stdlib/blob/master/sources/common/HalfOpenRange.kt
    ➕ 1
    i
    l
    • 3
    • 6
  • d

    dr.dreigh

    05/10/2019, 10:51 AM
    Could a “safe” version of the standard lib ever exist? Which could be used to replace with the normal standard lib, but without the functions that throw runtime exceptions, and instead returned nullable types or Either style sum types? Alternatively the unsafe functions could somehow fail the build if you use them. Kind of like how you can use Prelude replacements in Haskell.
    s
    • 2
    • 3
  • m

    Marc Knaup

    05/10/2019, 1:20 PM
    Almost everything having
    .isEmpty()
    has
    .isNotEmpty()
    .
    ClosedRange
    doesn't. I suggest to add it 🙂
    s
    v
    • 3
    • 3
  • j

    jw

    05/20/2019, 7:07 PM
    Array.copyOf
    returns an array which retains the variance. I.e.,
    Array<out String>
    stays as
    out String
    despite me taking a copy to modify its contents. Right now I'm just doing an unsafe cast, but it feels unfortunate (even more than how unfortunate it is to already be using arrays 😢 )
    i
    • 2
    • 1
  • d

    Dias

    05/21/2019, 4:46 PM
    How come reduce() doesn't work on empty collections? Shouldn't it just return seed value?
    s
    t
    • 3
    • 9
  • j

    josephivie

    05/23/2019, 4:28 PM
    I know it's not much, but I find myself using this all the time:
    fun <T> Iterable<T>.forEachBetween(item: (T)->Unit, between: ()->Unit)
    which runs the
    between
    block between each call of
    item
    , but doesn't get called at the very beginning or end
    e
    • 2
    • 6
  • k

    karelpeeters

    05/25/2019, 9:40 AM
    How do you get a instance of
    kotlin.random.Random
    ? I don't want to use the
    Random.Default
    since this is in a multithreaded context. The docs (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.random/-random/index.html) say
    To get a seeded instance of random generator use Random function.
    But that
    Random
    function just links back to the same page. Am I missing something?
    e
    i
    • 3
    • 7
  • r

    raulraja

    05/31/2019, 9:04 AM
    Hello Everyone, We have an issue in Arrow with the implementations of the suspension intrinsics in the std library. Currently the Arrow library uses continuations to enhance syntax when computing over types not just from Arrow but also for third party types we integrate with such as coroutines, rx, reactor, etc. For example, with KotlinX Couroutines
    Flow
    a user may destructure and compute over the Flow with:
    val flow = flowOf(1, 2, 3, 4, 5)
    fx {
      val n = !flow
      n + 1 //n is each of the elements in the flow
    }
    // flowOf(2, 3, 4, 5, 6)
    This same idiom can work with
    Deferred
    ,
    Observable
    ,
    IO
    , and pretty much anything that contains or can implement a
    flatMap
    method. For this to work with pure values and across all data types we have to reset the continuation stack so the continuation can be invoked multiple times. We would like to request that some kind of mechanism for library authors to be able to access the intrinsics of the
    kotlin.coroutines.jvm.internal.ContinuationImpl
    . At the moment resetting the coroutine stack is an exercise of heavy java reflection when this could be avoided if we had protected access to those fields or a means to obtain/clone the continuation state. https://github.com/arrow-kt/arrow/blob/7d54b31fe240688b4481b8f91767cbb82b9ad78c/modules/core/arrow-typeclasses/src/main/kotlin/arrow/typeclasses/ContinuationUtils.kt#L7 The use of reflection and manual copying the fields like that imposes unnecessary overhead and does not give us a solid solution going forward. As far as I understand suspension, suspension has been added to the Kotlin std library so other libraries can build on top of it. This is great because we don’t have the issues in Kotlin I had in Scala from people abusing
    Future
    just because it was in the std lib and opens the doors for others to create async/concurrent and in general suspended based frameworks just with the suspension apis. While this in concept is great, at the moment it just seems to be serving KotlinX Coroutines Core library use cases. There is other libraries like Arrow Fx where single shot / eager async continuations are not enough to cover these use cases. Can we get access to those fields without reflection or does anyone know of an alternative to accomplish this that does not require dealing with the
    ContinuationImpl
    stack? We are happy to collaborate with changes in the std lib or whatever it takes to get passed this issue.
    o
    e
    p
    • 4
    • 20
  • m

    Mark

    06/01/2019, 10:28 AM
    Is there an extension function on Collection that accepts a MutableList and simply adds all its own items to it (i.e. like addAll() in reverse). At the moment I have to do this:
    .also {
        targetList.addAll(it)
    }
    p
    s
    • 3
    • 4
  • t

    Tom Adam

    06/03/2019, 5:11 PM
    When it comes to iteration and ranges one can write something like:
    (5 downTo 3  step 3).forEach { println(it) }
    or
    (5 downTo 3).filter { it % 2 == 0}
            .forEach { println(it) }
    However, if filter would be infix, one could also write
    (5 downTo 3  filter { it % 2 == 0})
            .forEach { println(it) }
    which would be totally in sync with the infix syntax of
    step
    , and possibly would mean a more consistent API. Any thoughts?
    ➖ 3
    ➕ 1
    e
    h
    +2
    • 5
    • 9
  • i

    ilya.gorbunov

    06/06/2019, 1:36 PM
    📣 Please welcome our first step to the standard way of working with time in Kotlin: Duration and time interval measurement API https://github.com/Kotlin/KEEP/blob/durations/proposals/stdlib/durations-and-clocks.md The proposal can be discussed in this issue: https://github.com/Kotlin/KEEP/issues/190
    :kotlin: 1
    🎉 27
    j
    m
    +3
    • 6
    • 26
  • m

    Marc Knaup

    06/12/2019, 3:12 AM
    What about moving
    Url
    from ktor.http to stdlib? 🤔 • it's very commonly needed • it's for more than HTTP or even networking • Ktor is an implementation detail - could also be another HTTP client • when using different libraries (networking and other) they all use different
    Url
    classes because there's no common denominator
    👍 3
    😮 1
    n
    e
    n
    • 4
    • 10
  • v

    voddan

    06/13/2019, 12:03 PM
    For my use case I wanted to have
    list.take(n)
    in a way that would remember the last accessed position and give me the next
    m
    elements on a consecutive
    list.take(m)
    https://stackoverflow.com/questions/56578561/how-can-i-take-varying-chunks-out-of-a-kotlin-sequence My solution was to produce an
    Iterator
    from the list and use
    take(n)
    on it. Unfortunately that produces a of-by-one error because of the way
    take
    is implemented in stdlib. To fix this one would have to modify a few lines in the [implementation](https://github.com/JetBrains/kotlin/blob/41ce88cb9b8e32da6121e79c229b2563f46fd161/libraries/stdlib/common/src/generated/_Collections.kt#L778 ) replacing
    for (item in this) {
            if (count++ == n)
                break
            list.add(item)
        }
    with
    for (item in this) {
            list.add(item)
            if (++count == n)
                break
        }
    Could such a change be considered?
    i
    • 2
    • 3
  • b

    bbaldino

    06/13/2019, 7:37 PM
    is there a collection in kotlin like java's
    Vector
    which will default instantiate the instances? i want to create a collection of a generic type (from a class generic param) but don't want to have to pass in a lambda to tell the class how to default initialize. i.e.:
    class Foo<StatType> {
        val stats = Vector<StatType>(8)
    }
    p
    e
    • 3
    • 8
  • e

    elect

    06/14/2019, 8:57 AM
    onEachIndexed
    ?
    h
    k
    • 3
    • 3
  • e

    elect

    06/14/2019, 9:26 AM
    also
    operator fun <R> KMutableProperty0<R>.setValue(host: Any?, property: KProperty<*>, value: R) = set(value)
    operator fun <R> KMutableProperty0<R>.getValue(host: Any?, property: KProperty<*>): R = get()
    for setting local
    var
    from variable references
    g
    d
    k
    • 4
    • 9
  • h

    Hullaballoonatic

    06/16/2019, 6:48 PM
    Number
    changed from Abstract Class to Interface, given it is purely composed of abstract methods.
    👍 2
    k
    z
    +2
    • 5
    • 30
  • g

    gregorbg

    06/25/2019, 8:29 AM
    What is the reason for
    Map<K, V>.filterValues
    working directly on the values (i.e. it expects
    (V) -> T
    ) as opposed to
    Map<K, V>.mapValues
    working on the entire entry (i.e. it expects
    (Map.Entry<K, V>) -> T
    )? Same question applies to the signature of
    filterKeys
    vs.
    mapKeys
    and similar functions.
    v
    s
    d
    • 4
    • 4
  • g

    guenther

    06/27/2019, 3:24 PM
    Floating Point Rounding: With the JVM it's a mess to round an e.g.
    Double (12.456778)
    to a certain precision. This would be something really useful like
    12.34567.roundToPrecision(...)
    (don't nail me on the function name, I'd just want to express that rounding would be useful. What do you think?
    k
    p
    +2
    • 5
    • 32
  • h

    Hullaballoonatic

    07/01/2019, 8:55 PM
    nullable constructor params can be assigned at initialization to non-nullable lateinit properties. If they are null, then the property remains uninitialized, otherwise it is set.
    class Foo(bar: Int?, baz: Int?, boz: Int?) {
        lateinit var bar: Int = bar // acceptable
        lateinit var baz = baz // implicitly assigned as non-nullable
        lateinit var boz: Int? = baz // unacceptable
    }
    p
    • 2
    • 9
  • b

    bbaldino

    07/09/2019, 8:38 PM
    am i understanding it right that using
    withDefault
    for a map doesn't actually insert that default into the map when a key which isn't present is found, it just returns an instance of that default?
    n
    k
    d
    • 4
    • 12
  • m

    Marc Knaup

    07/10/2019, 7:18 PM
    Any plans for a standard multiplatform
    Locale
    yet? It would be needed for a multiplatform time library to support formatting 🙂
    s
    c
    • 3
    • 10
  • a

    arekolek

    07/12/2019, 12:14 PM
    Could some contract be added to
    Int.sign
    to support this?
    val foo = when (a.compareTo(b).sign) {
        -1 -> SomeEnum.LEFT
        0 -> SomeEnum.NONE
        1 -> SomeEnum.RIGHT
    }
    Does the contract API support something like this?
    k
    m
    • 3
    • 8
  • b

    bbaldino

    07/13/2019, 6:04 AM
    i notice that, when subclassing
    MutableMap
    , overriding
    compute
    gives the signature
    override fun compute(key: T, remappingFunction: BiFunction<in T, in U?, out U?>): U?
    , but overriding
    computeIfAbsent
    gives
    override fun computeIfAbsent(key: T, mappingFunction: Function<in T, out U>): U
    (note the missing
    ?
    after
    U
    on the return type) but
    computeIfAbsent
    is documented as being able to return null. is this a bug?
    computeIfPresent
    also correctly uses
    U?
    as the return type.
    u
    • 2
    • 9
  • h

    Hullaballoonatic

    07/19/2019, 6:32 PM
    operator fun <T> Pair<T, T>.iterator() = object : Iterator<T> {
        var i = 0
        
        override fun hasNext() = i < 2
        
        override fun next() = when (i++) {
            0 -> first
            1 -> second
            else -> throw NoSuchElementException()
        }
    }
    p
    d
    +2
    • 5
    • 18
  • h

    Hullaballoonatic

    07/19/2019, 6:57 PM
    "coordinate" iteration, e.g
    (0 to 0)..(1 to 1)
    iterates through
    0 to 0, 0 to 1, 1 to 0, 1 to 1
    . Might be a stretch, but I think it's intuitive.
    operator fun Pair<Int, Int>.rangeTo(that: Pair<Int, Int>) = object : Iterable<Pair<Int, Int>> {
        override fun iterator() = object : Iterator<Pair<Int, Int>> {
            var i = this@rangeTo.first
            var j = this@rangeTo.second
            
            val m = that.first - i
            val n = that.second - j
    
            override fun hasNext() = i <= m && j <= n
    
            override fun next(): Pair<Int, Int> {
                val res = i to j
                
                if (j == n) {
                    j = 0
                    i++
                } else {
                    j++
                }
                
                return res
            }
        }
    }
    could also be expanded to higher dimensions with
    List<Int>.rangeTo(other: List<Int>)
    ,
    IntArray
    , etc
    d
    k
    • 3
    • 10
  • h

    Hullaballoonatic

    07/20/2019, 11:57 PM
    Expand on
    String::split
    to be as great as `joinToString`:
    fun String.split(
        delimiter: CharSequence = ", ",
        prefix: CharSequence = "",
        postfix: CharSequence = "",
        limit: Int = -1
    ): List<String>
    fun <R> String.split(
        delimiter: CharSequence = ", ",
        prefix: CharSequence = "",
        postfix: CharSequence = "",
        limit: Int = -1,
        transform: (CharSequence) -> R
    ): List<R>
    ➖ 1
    d
    • 2
    • 1
  • s

    serebit

    07/23/2019, 11:10 PM
    Superclass information in KType (via typeOf) would be nice
    ➕ 1
    d
    • 2
    • 5
  • j

    jw

    07/25/2019, 9:23 PM
    so ClockMarks aren't Comparable, which makes sense since you cannot really meaningfully compare them across Clocks, but also it's a bit annoying since frequently you're in a single Clock "namespace" where it would be nice to not have to continually unwrap them
    i
    • 2
    • 11
Powered by Linen
Title
j

jw

07/25/2019, 9:23 PM
so ClockMarks aren't Comparable, which makes sense since you cannot really meaningfully compare them across Clocks, but also it's a bit annoying since frequently you're in a single Clock "namespace" where it would be nice to not have to continually unwrap them
i

ilya.gorbunov

07/25/2019, 9:58 PM
What do you mean by unwrapping?
j

jw

07/25/2019, 10:07 PM
calling
elapsed()
For example:
var expiration = expirationClockMark
val mark = clock.mark()
if (mark.elapsed() >= expiration.elapsed()) {
where it feels like it should be
var expiration = expirationClockMark
val mark = clock.mark()
if (mark >= expiration) {
There's no type system tricks (as far as I know) to restrict this at compile time to two instances which originated from the same
Clock
. But maybe a runtime check is enough? Things like
java.nio.path.Path
come to mind where it's tied to a
FileSystem
and you cannot meaningfully do operations on two `Path`s from different `FileSystem`s. Despite this, there are methods which work on two instances (like
Path.resolve(Path)
) which just runtime-check the invariant. The only problem I see is that it would become the responsibility of any custom `Clock`/`ClockMark` implementation to ensure they implement this behavior.
i

ilya.gorbunov

07/25/2019, 10:57 PM
if (mark.elapsed() >= expiration.elapsed())
If these two marks are from the same clock, this expression would be almost always true or always false, because
elapsed
values of both of them increment simultaneously. What are you trying to achieve by this comparison?
j

jw

07/25/2019, 10:59 PM
er, i assumed a mark was an immutable snapshot of the current elapsed time (equivalent to calling something like
System.nanoTime()
)
i

ilya.gorbunov

07/25/2019, 11:00 PM
The mark itself stands still, it's just the time goes forward 🙂.
You can implement expiration as following:
val expiredClockMark = clock.mark() + timeout
...
if (!expiredClockMark().elapsed.isNegative()) { 
    // expired
}
j

jw

07/25/2019, 11:03 PM
ok. that makes a lot more sense in terms of the behavior i'm seeing then! i need to compare elapsed to my expected duration rather than compare marks
i

ilya.gorbunov

08/08/2019, 4:55 PM
We're currently reevaluating ClockMark design to minimize its misuse. Could you help by telling how were your clock mark variables was called originally (if it was different from the second comment), how were you obtaining
expirationClockMark
value and how did your code look in the end after rewriting?
j

jw

08/08/2019, 5:01 PM
Having not read the documentation and going solely based on the API names, I was originally interpreting clock marks as being fixed points on the timeline of the clock such that i could take two of them and then compare them to each other (did one come after another,
clock.mark() > expirationClockMark
) or do math on them (take this mark plus a duration to produce a new mark,
expirationClockMark = currentMark + expirationDuration
). This probably stems from java.time.Clock use which produces Instants which are points on the timeline where this code would have worked. After re-working, based on your help, the final code is at https://github.com/JakeWharton/SdkSearch/blob/master/backend/dac-proxy/src/main/java/com/jakewharton/sdksearch/proxy/memoize.kt
:tnx: 1
The code was ported from using
clock: () -> Int = System::nanoTime
and
expirationNanos: Int
to
Clock
and
ClockMark
, so that also led me to naively assume they represented the same concepts
View count: 1