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

    David Gracia

    08/30/2021, 8:58 PM
    Hello everybody. I think I have found a gap in the koltin stlib and I would like to make a contribution to it. But first I would like to discuss it with you to be sure it is worthwhile. A few days ago, a student asked me for help to find an efficient algorithm in kotlin to solve this exercise https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem . After analyzing it, I realized that it is necessary to use a collection such that: - it is mutable - it has random/direct access (read-only) - it keeps the elements sorted at all times (invariant) - it can have duplicate elements I started looking for data structures in the kotlin and java stlib and did not find any that met the requirements. I searched stackoverflow and found this thread https://stackoverflow.com/questions/8725387/why-is-there-no-sortedlist-in-java. None of the alternatives work to solve the exercise efficiently. So I implemented the data structure myself and solved the exercise. Personally I think it is worthwile because the hackerrank problem seems to me to be a likely scenario in the fintech domain. What do you think?
    e
    m
    +2
    • 5
    • 11
  • x

    xxfast

    08/31/2021, 12:27 AM
    Hi all, whats the stdlib way to achieve this?
    val actual = listOf("a","b","c","d")
    val expected = listOf("ab","bc","cd")
    d
    e
    s
    • 4
    • 8
  • r

    Rob Elliot

    09/14/2021, 9:09 AM
    I’m surprised by the definition of
    fun <T, R> T.runCatching(block: T.() -> R): Result<R>
    - it catches
    Throwable
    , and hence
    Error
    , including things you almost certainly don’t want to catch like
    OutOfMemoryError
    . It also makes no attempt to propagate
    InterruptedException
    (or reset the interrupted status of the Thread when catching it). Am I missing something? Or just woefully out of date in my JVM exception handling?
    👀 2
    e
    o
    +3
    • 6
    • 11
  • e

    edrd

    09/16/2021, 8:34 PM
    Anyone else thinks it would be nice to have a
    String.prepend(value: String)
    in the stdlib? I need it quite often and
    .let { "prefix$it" }
    doesn't express intent so well.
    s
    m
    g
    • 4
    • 7
  • x

    xxfast

    09/20/2021, 1:11 AM
    Hi all, whats the best way to achieve this?
    val actual = listOf(
      Item(type = A, value = 1),
      Item(type = B, value = 2),
      Item(type = B, value = 3)
    )
    
    val expect = mapOf(
      A to listOf(Item(type = A, value = 1)),
      B to listOf(Item(type = B, value = 2), Item(type = B, value = 3)),
      C to emptyList()
    )
    d
    t
    +2
    • 5
    • 7
  • d

    dimsuz

    09/20/2021, 1:51 PM
    Probably this is a super FAQ, but if another module in my project has
    data class Value(val foo: Foo?)
    and I do
    if (value.foo != null) foo.bar() else doStuff()
    , there's an error "smart cast is impossible". But if I know that a) it's val b) no multithreading is used, can I "smarten" the compiler? Perhaps by adding some
    contract
    somewhere? Is there a YouTrack issue along these lines maybe?
    d
    e
    t
    • 4
    • 9
  • d

    darkmoon_uk

    09/22/2021, 2:56 AM
    ❓ Has the cost of using lazy on the JVM changed at all since

    this talk▾

    at Google in 2019? The gist of this talk is to warn developers against using
    lazy
    (and possible other Property Delegation) - the foundation of their argument appears to be that use of reflection in property delegation is too costly for most use cases. Unfortunately they don't give any examples of where the 'tipping point' of complexity lies; where
    lazy
    does become worth it. This has put my team off from using lazy even for cases where moderately complex objects are being created. I'm suspect of two things in this talk: firstly their poor choice of example - obviously it's going to be inefficient to use this to allocate an
    Int
    , but what about smaller-to-moderately sized classes? No benchmarks provided or discussion of initial
    lazy
    cost vs. subsequent
    lazy
    where presumably some aspects of any reflection would have become cached. Thoughts?
    e
    j
    • 3
    • 7
  • p

    PHondogo

    09/22/2021, 7:44 AM
    Hello! Is there builtin solution to check for overflow when converting Long.toInt() ?
    m
    e
    +2
    • 5
    • 11
  • h

    Hullaballoonatic

    09/26/2021, 11:03 PM
    why does
    List
    have
    chunked()
    but
    DoubleArray
    does not?
    j
    c
    • 3
    • 2
  • o

    Orhan Tozan

    09/27/2021, 1:41 PM
    Why does the call to sendUser2() throw a compiler error?
    value class UserId(private val value: Int)
    
    fun sendUser1(userId: UserId) = ...
    fun sendUser2(userId: Int) = ...
    
    // Compiler error: required: UserId, found: Int. Makes sense because an Int isn't always a UserId.
    sendUser1(1)
    
    // Compiler error: required: Int, found: UserId. Does not make sense because a UserId is always an Int.
    sendUser2(UserId(1))
    Why doesn't the compiler see that type UserId is of type Int? It makes it harder for a project to adopt value classes if the new types aren't compatible with it's super type
    f
    h
    +4
    • 7
    • 20
  • n

    natario1

    09/28/2021, 8:00 AM
    Navigating through stdlib code I found one function annotated like this:
    @Suppress("EXTENSION_SHADOWED_BY_MEMBER") // false warning, extension takes precedence in some cases
    Does anyone know in which cases the extension takes precedence? This one is
    Collection<T>.containsAll(elements: Collection<T>)
    for instance.
    i
    • 2
    • 1
  • e

    elect

    09/28/2021, 12:59 PM
    IntRange
    and similars have methods to easily extract collections.
    ClosedRange
    instead no.. this is a pity
    h
    e
    • 3
    • 5
  • m

    mikehearn

    10/04/2021, 4:48 PM
    Hello. Does anyone know the justification for kotlin.io being a set of extensions to
    java.io.File
    instead of
    java.nio.file.Path
    ? I assume this is to do with the legacy Java 1.6 support but it's quite awkward for programs that want to benefit from the NIO features like in-memory file systems, etc.
    n
    e
    +3
    • 6
    • 15
  • m

    mikehearn

    10/04/2021, 4:48 PM
    I can't find anything in YouTrack about this and was wondering if there are any plans to switch the implementation to using
    java.nio.file.Path
    and then leave the current methods as forwarders that convert the File to a Path.
    e
    • 2
    • 1
  • d

    darkmoon_uk

    10/07/2021, 1:26 AM
    Not a problem but a mere curiosity; is there any more 'first class' way of writing
    { it }
    where for a single parameter lambda that merely pipes-through its input value?
    e
    o
    j
    • 4
    • 7
  • t

    Tomasz Krakowiak

    10/10/2021, 3:01 PM
    message has been deleted
    h
    • 2
    • 1
  • c

    Colm Murphy

    10/11/2021, 11:03 AM
    I just discovered that the Byte and Short classes (and their unsigned counterparts) have no
    shl
    or
    shr
    infix functions. Is this intentional or not?
    t
    • 2
    • 1
  • j

    Javier

    10/12/2021, 10:50 AM
    Crosspost: https://kotlinlang.slack.com/archives/C0B9K7EP2/p1634034253030700
    ➕ 1
    h
    r
    • 3
    • 2
  • j

    jimn

    10/12/2021, 3:13 PM
    I am looking at removing java date/time from my code where it is almost painless. in the matter of java
    Instant
    ctor, and serialization, we need 12 bytes, a long for ms and int for nanos. The kotlin
    Duration
    analog class only appears to support at best a Long or Double, neither which supports the same resolution. Instead of a break between Java's Date, DateTime, and Instant classes which supports DateTimes with nanosecond backingstores, Duration apparently presumes to do all three and for events on astronomical scales of time resolution appears to force the coder to box a relative 64 bit expanse of measurement for the non-jvm stdlib. to my understanding BigInteger math is a sliding set of 32 bit Int operations going up and down to MAXINT resolution and is claimed to be faster in the C2 on intel than native wide instructions in some cases. Is Duration with a promotion option to BigInteger backingstore reasonable? The solution would address a) usecases that want higher res, and b) a sideload BitSet/BigInt serialization option that can match impedences with e.g. Instance and other DateTime libraries which don't all apparently assume 64 bits and only 64 bits.
    i
    • 2
    • 4
  • j

    Joffrey

    10/13/2021, 2:56 PM
    Are
    maxBy
    and
    minBy
    going to be un-deprecated in 1.6 with a new strict behaviour? Or is it planned for a later version?
    i
    • 2
    • 2
  • e

    elect

    10/13/2021, 6:01 PM
    what about changing on
    Map<K, V>
    the
    getOrElse
    by passing as argument the key which wasn't found?
    public inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: () -> V): V
    to
    public inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: (V) -> V): V
    My use case is to search for the same key somewhere else
    e
    r
    j
    • 4
    • 11
  • s

    smichel17

    10/15/2021, 1:09 PM
    What would you think about an indexed
    Sequence.takeWhile
    ? E.g. one of these:
    fun <T>Sequence<T>.takeThenWhile(count: Int, predicate: (T) -> Boolean): Sequence<T> {
        var i = 0
        return this.takeWhile{ i < count || predicate(it) }.onEach { i++ }
    }
    
    
    fun <T>Sequence<T>.takeWhileIndexed(predicate: (Int, T) -> Boolean): Sequence<T> {
        var i = 0
        return takeWhile { predicate(i, it) }.onEach { i++ }
    }
    Both
    take
    and
    takeWhile
    could be implemented in terms of this function
    fun <T>Sequence<T>.take(count: Int) = takeThenWhile(count) { false }
    fun <T>Sequence<T>.takeWhile(predicate: (T) -> Boolean) = takeThenWhile(0, predicate)
    
    fun <T>Sequence<T>.take(count: Int) = takeWhileIndexed { i, _ -> i < count }
    fun <T>Sequence<T>.takeWhile(predicate: (T) -> Boolean) = takeWhileIndexed { _, t -> predicate(t) }
    g
    e
    • 3
    • 18
  • r

    rocketraman

    10/18/2021, 6:31 PM
    partition
    only supports two outputs. What about adding something like this to the stdlib?
    /**
     * Similar to the stdlib partition method, but supports an arbitrary number of output lists. The number
     * of outputs must be known in advance.
     */
    @Throws(IndexOutOfBoundsException::class)
    fun <T> List<T>.partitionInto(size: Int, predicate: (T) -> Int): List<List<T>> {
      val lists = listOf(*(0.until(size).map { mutableListOf<T>() }.toTypedArray()))
      for (element in this) {
        val index = predicate(element)
        lists[index].add(element)
      }
      return lists
    }
    m
    e
    j
    • 4
    • 34
  • g

    groostav

    10/18/2021, 8:14 PM
    uhh, has there been any discussion about using something like
    inline class
    to simplify java's`compareTo` function? I was thinking that an
    inline class
    that's wrapping the results would be handy and do a lot for readability. If not, can we
    typealias ComparisonResult = Int
    and put some docs there? I feel like kotlin can do a lot to add sugar and/or lipstick to this pig in java.
    👍 1
    💯 1
    e
    • 2
    • 6
  • n

    natpryce

    10/22/2021, 7:23 AM
    Is there a function in the kotlin stdlib to split a list into a list of sublists with a predicate to choose where to separate each sublist, and where the result preserves the order of elements.
    List::chunked
    doesn’t do what I want, nor does
    List::windowed
    .  E.g. if I have a list, x = [“a”, “b”, “C”, “d”, “E”, “F”, “g”] and I want to split it into sublists where the case is the same within the sublist, I could pass in a predicate to this function something like…
    x.split { x, b -> a.isUpperCase() != b.isUpperCase() }
    giving me:
    [["a", "b"], ["C"], ["d"], ["E", "F"], ["g"]]
    I often need this operation, but always end up writing it with imperative code.  Is there something in the stdlib I’m missing.
    ☝️ 1
    m
    e
    +2
    • 5
    • 24
  • m

    mazorius

    10/22/2021, 1:01 PM
    Hi, I see that
    .capitalize()
    is be replaced by
    .replaceFirstChar()
    but the latter one is not shown in my IDE? I only got
    replaceFirst
    j
    e
    • 3
    • 5
  • r

    Ruckus

    10/23/2021, 12:11 AM
    Currently we have
    enumValues<T>(): Array<T>
    and
    enumValueOf<T>(name: String): T
    for enums. It would be nice if there was also
    enumValueAt<T>(ordinal: Int): T
    . It's pretty easy to work around with
    enumValues()[ordinal]
    , so not a huge deal, but it feels a bit clunky. Another nice to have for would be something like
    enumSize<T>(): Int
    . Again, easy to work around with
    enumValues().size
    , but same argument as above.
    ➕ 7
    e
    j
    k
    • 4
    • 4
  • h

    holgerbrandl

    11/01/2021, 7:39 PM
    Just of curiosity: Why is
    ceil()
    not an extension on Double?
    c
    j
    e
    • 4
    • 14
  • m

    maxmello

    11/02/2021, 4:56 PM
    joinToString
    has
    truncated: CharSequence = "..."
    as an optional parameter. It would be nice if
    String.take(n: Int)
    could have the same optional parameter that is appended in case
    n
    is smaller than the length of the String. Maybe it could also be a different method name, as this would be more a use case for logging/displaying a string similar to joinToString, rather than “working on a string” by using substring for maybe some logical operation on the string. It could be something like
    abbreviate
    or maybe
    cut
    a
    • 2
    • 2
  • a

    Ansh Tyagi

    11/04/2021, 5:30 PM
    Hey everyone! so i was creating a file during runtime and then accessing it (File.readLines()) but it throws an error of file not found? Is it because we cannot read the file created during runtime? If so is there any work around happy to discuss
    b
    e
    • 3
    • 14
Powered by Linen
Title
a

Ansh Tyagi

11/04/2021, 5:30 PM
Hey everyone! so i was creating a file during runtime and then accessing it (File.readLines()) but it throws an error of file not found? Is it because we cannot read the file created during runtime? If so is there any work around happy to discuss
b

Big Chungus

11/04/2021, 5:32 PM
Did you actually write the file? Just constructing File instance does not create a file
Also this is not really kotlin specific
a

Ansh Tyagi

11/04/2021, 5:36 PM
so right now what happens is there is a ProcessBuilder which creates a file at runtime and i just need to read some outputs of those file
i too feel its not kotlin specific but when i hardcode the file path it reads it
b

Big Chungus

11/04/2021, 5:37 PM
Might be a race condition then. Check if the file exists before accessing it via File::exists
Also check your file's canonicalPath to verify that it's pointing to where you expect
a

Ansh Tyagi

11/04/2021, 5:39 PM
i even tried making Thread.sleep for a few sec but no outcome. File::exists show that this file does not exists but it does.
I’ll check once with the canonicalpath
b

Big Chungus

11/04/2021, 5:39 PM
Most likely paths are resolving differently to what you expect
This is likely due to processed running in different workingDirs and using relative paths
👍 1
To be honest this smells like bad architecture
Easiest fix, convert file to absolute file before writing and passing it along
a

Ansh Tyagi

11/04/2021, 7:25 PM
Great! altho i switched the working dirs to the project root. That solved my problem
e

ephemient

11/04/2021, 8:07 PM
this sounds like gradle, in which case 1. you cannot rely on a particular working directory within the build script, it depends on how Gradle was launched 2. you should use
exec {}
or an
Exec
task instead of
ProcessBuilder
3. :not-kotlin:
View count: 4