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

    jw

    07/26/2019, 1:41 AM
    TestClock
    feels like it should have `plusAssign`/`minusAssign` of a
    Duration
    as a convenience.
    clock += 2.minutes
    i
    • 2
    • 7
  • h

    holgerbrandl

    08/07/2019, 11:44 PM
    Hi there, why would 2 different lists return the same hash?
    println(listOf(3, 263).hashCode())
     println(listOf(5, 201).hashCode())
    // -> 1317
    
    println(Arrays.asList(3, 263).hashCode())
    println(Arrays.asList(5, 201).hashCode())
    // --> 40830
    It's a more general problem as also the java example suffers from exactly the same problem. Interestingly, arrays with the same data give differnt hashes as documented at https://github.com/holgerbrandl/krangl/issues/75
    i
    d
    +2
    • 5
    • 10
  • a

    asad.awadia

    08/10/2019, 10:51 PM
    How do you convert a data class to a map object?
    m
    • 2
    • 1
  • v

    voddan

    08/11/2019, 9:57 AM
    sometimes you can back your fields with a map
    var x: Int by map
    k
    • 2
    • 1
  • p

    Pavel Apisov

    08/30/2019, 9:20 AM
    Hello people 🖖 Does anybody know why
    any
    or
    all
    returns
    true
    with an empty list no matter what the predicate? Seems counterintuitive. I tried to google it quickly but no luck. Just wondering, maybe someone's aware of it and can explain 🙂
    s
    c
    • 3
    • 4
  • n

    nfrankel

    09/05/2019, 8:30 PM
    hi i just noticed the following: in java,
    Stream.reduce(accumulator: BinaryOperator<T>)
    returns an
    Optional<T>
    it makes sense because if the stream is empty, the result will be empty there’s another flavor providing an initial value and that returns a
    T
    Stream.reduce(identity: T, accumulator: BinaryOperator<T>): T
    that makes sense too however, in kotlin both
    Sequence.reduce()
    (without initial value) and
    Sequence.fold()
    (with an initial value) return the same non-nullable type actually, the code throws an exception if the sequence is empty which seems not in line with what i would expect a nullable value why this behavior? am i missing something?
    i
    d
    • 3
    • 4
  • m

    miha-x64

    09/06/2019, 4:56 PM
    reduce
    would be great extension for
    NonEmptyIterable
    https://youtrack.jetbrains.com/issue/KT-21217
    m
    d
    • 3
    • 7
  • d

    dr.dreigh

    09/06/2019, 6:51 PM
    oh, sorry Mike, I see what you mean, reduce would work on a NonEmptyIterable, I thought you meant as a return from
    sequence.reduce
    n
    • 2
    • 5
  • s

    spand

    09/18/2019, 9:08 AM
    Is there a
    List<E>.associateWithIndex(): Map<E, Int>
    or something similar that I am missing. (edited)
    m
    a
    • 3
    • 4
  • u

    uliluckas

    09/24/2019, 9:09 PM
    Hi there, is there a reason not to have a type parameter for the delegate on a
    KProperty
    ? if there was, one could write extension functions, depending on the delegate type. I.e.
    fun KProperty<*, BehaviorRelayDelegate>.subscribe(O: Observer)
    and use it like
    val v : Int by BehaviorRelayDelegate(0)
    ::v.subscribe { Log("Value changed to $it" }
    v = 2
    val v1 = v
    i
    • 2
    • 1
  • n

    napperley

    09/25/2019, 11:11 PM
    This is a repost (from #general) about extending the Boolean type: https://kotlinlang.slack.com/archives/C0922A726/p1569444125303200
    i
    k
    • 3
    • 3
  • m

    Marc Knaup

    09/26/2019, 7:27 AM
    Can we kotlinify Java’s
    Objects.hash(foo, bar, baz, …)
    to something like this?
    hash { foo x bar x baz x … }
    Just the boxing is a little tricky as well as getting it to work with just a single non-
    Int
    value without introducing boxing. Implementation:
    inline fun hash(block: HashScope.() -> Int) =
    	HashScope.block()
    
    object HashScope {
    
    	inline infix fun Any?.x(hashable: Any?) =
    		(31 * hashCode()) + hashable.hashCode()
    
    	inline infix fun Any?.x(hashable: Int) =
    		(31 * hashCode()) + hashable
    
    	inline infix fun Int.x(hashable: Any?) =
    		(31 * this) + hashable.hashCode()
    
    	inline infix fun Int.x(hashable: Int) =
    		(31 * this) + hashable
    }
    
    class Example(val foo: String, val bar: List<Any>?, val baz: Int) {
    
    	override fun hashCode() =
    		hash { foo x bar x baz }
    }
    j
    m
    • 3
    • 7
  • m

    Marc Knaup

    09/26/2019, 7:43 AM
    Another question: Why doesn’t
    ClosedRange
    have operators for destructuring?
    m
    • 2
    • 6
  • d

    Dominaezzz

    10/10/2019, 6:24 PM
    Proposal.
    @kotlin.internal.InlineOnly
    public inline fun buildByteArray(builderAction: ByteArrayOutputStream.() -> Unit): ByteArray
    j
    • 2
    • 6
  • m

    Mark

    10/11/2019, 10:49 AM
    Is there a better way to write this:
    val CJK_EXTENSIONS_STR = fun (): String {
        var result = "\\p{InCJK_UNIFIED_IDEOGRAPHS_EXTENSION_A}\\p{InCJK_UNIFIED_IDEOGRAPHS_EXTENSION_B}\\p{InCJK_UNIFIED_IDEOGRAPHS_EXTENSION_C}\\p{InCJK_UNIFIED_IDEOGRAPHS_EXTENSION_D}"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            result += "\\p{InCJK_UNIFIED_IDEOGRAPHS_EXTENSION_E}"
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                result += "\\p{InCJK_UNIFIED_IDEOGRAPHS_EXTENSION_F}"
            }
        }
        return result
    }.invoke()
    ✅ 1
    m
    • 2
    • 12
  • d

    Dominaezzz

    10/11/2019, 5:26 PM
    Is there a YouTrack issue for
    Closeable
    in stdlib? I remember the verdict being stdlib itself doesn't use it so it won't provide it, but there should a ticket somewhere.
    j
    i
    • 3
    • 4
  • s

    spand

    10/22/2019, 9:31 AM
    Any particular reason
    Iterable<T>.groupByTo
    requires destination to be a list and not a collection ?
    d
    • 2
    • 2
  • b

    Bob Glamm

    10/23/2019, 4:47 PM
    Suggest adding
    fun Pair<A, B>.flip(): Pair<B, A> = Pair(second, first)
    to the standard library
    🤔 3
    😒imple_smile: 2
    m
    i
    g
    • 4
    • 4
  • p

    PHondogo

    10/30/2019, 6:13 AM
    Hi! I couldn't find in stdlib common implementation fo formatting Double to String by pattern. Is there any crossplatform solution for that?
    g
    • 2
    • 5
  • l

    LeoColman

    10/30/2019, 7:38 PM
    Encoding/Decoding Base64 without depending on Java methods
    s
    m
    • 3
    • 2
  • h

    Hullaballoonatic

    10/31/2019, 4:42 PM
    I see that kotlin is getting its own implementation of
    Duration
    in the stdlib, and I'm wondering if it could also have its own version of
    Date
    that cleans up the mess that is Java's
    Date
    ,
    DateTime
    ,
    LocalDate
    ,
    LocalDateTime
    g
    m
    +2
    • 5
    • 19
  • p

    PHondogo

    11/02/2019, 11:23 AM
    Hello! Is there any plans to support multiplatform BigDecimal?
    v
    • 2
    • 1
  • d

    Daniel Rust

    11/04/2019, 7:53 PM
    When is it best to use
    !!
    over
    checkNotNull
    ?
    ☝️ 1
    d
    g
    q
    • 4
    • 6
  • b

    bbaldino

    11/06/2019, 9:00 PM
    did something change with
    Result
    between 1.3.21 and 1.3.50? in 1.3.21 i can access it fine but can't find it in 1.3.50 (
    -Xallow-result-return-type
    doesn't help either)
    e
    • 2
    • 1
  • a

    Alpesh Vas

    11/07/2019, 7:06 PM
    What do you guys think?
    x
    k
    +4
    • 7
    • 25
  • j

    jimn

    11/11/2019, 9:12 AM
    when i run this.iterator() which calls invoke(Int) should i assume origin is the vtable for IDataframe::invoke(Int) ? do i need to manually delegate each method i wish to expose if I iwsh to use specialized methods I write in the delegator ?
    class FrameGrouper(
        private val origin: IDataFrame,
        vararg val gby: Int
    ) :  IDataFrame  by origin  {
        override fun invoke(row: Int) =...}
    k
    h
    • 3
    • 7
  • h

    Hullaballoonatic

    11/11/2019, 10:20 PM
    inline fun <T, reified R> Array<T>.mapToArray(transform: (T) -> R) = 
        Array(size) { transform(get(it)) }
    etc for
    List
    , primitive arrays...
    m
    • 2
    • 2
  • r

    Ruckus

    11/12/2019, 2:49 PM
    Just throwing this out there, does anyone think it would be a good idea to include such a function in std-lib:
    inline infix fun Any?.hash(other: Any?): Int = hashCode() * 31 + other.hashCode()
    It would simplify writing
    hashCode
    functions:
    class ABC<A, B, C>(val a: A, val b: B, val c: C) {
        override fun hashCode() = a hash b hash c
    }
    👍 7
    b
    s
    +2
    • 5
    • 12
  • h

    Hullaballoonatic

    11/20/2019, 6:46 PM
    Why is the function
    List(7) { it + 3 }
    a top level function instead of an static invoke operator? Is the latter somehow unintended usage of the language, or against standard code style? static invoke operator is just so much more efficient than constructors, given you can error check prior to instantiation, among many other things. I can see how it can read very alien to those not kotlin-savvy, however.
    j
    k
    i
    • 4
    • 4
  • d

    Dominaezzz

    11/20/2019, 10:27 PM
    Proposal.
    fun CharSequence.splitToSequences(
        vararg delimiters: String,
        ignoreCase: Boolean = false,
        limit: Int = 0
    ): Sequence<CharSequence>
    ➕ 2
    h
    j
    +2
    • 5
    • 15
Powered by Linen
Title
d

Dominaezzz

11/20/2019, 10:27 PM
Proposal.
fun CharSequence.splitToSequences(
    vararg delimiters: String,
    ignoreCase: Boolean = false,
    limit: Int = 0
): Sequence<CharSequence>
➕ 2
h

Hullaballoonatic

11/20/2019, 11:31 PM
yeah, i really want there to be a
String::split
method with all the params that
Collection::joinToString
has.
d

Dominaezzz

11/20/2019, 11:33 PM
The existing
splitToSequence
returns
String
instead of
CharSequence
. Which means more allocations. 😞
j

jimn

11/21/2019, 12:02 AM
CharSequence is worth avoiding performance-wise. it's a meaningless marker interface that requires workarounds in k-n to avoid O(n) access
adapting mappedbytebuffer to charsequence would be a good use for it.
e

elizarov

11/21/2019, 3:18 PM
But why?
d

Dominaezzz

11/21/2019, 3:22 PM
To be fair my current use case is quite specific. I have a large string of about 20,000 words separated by spaces and I want to count the number of occurrences of each word. I'm multi-threading. It's a bit rough to make large copies instead of slices.
j

jimn

11/21/2019, 3:41 PM
i can think of at least a couple of libraries like suffix search trees that might find this applicable to Sequence<T> where the jvm implementations (and my kotlin port) vary between <T:Byte> and <T:Int>
e

elizarov

11/21/2019, 3:43 PM
I’ve played with it at some point, and, unfortunately, the version with sequences does not give any siginificant performance benefits.
j

jimn

11/21/2019, 3:46 PM
nio ByteBuffer approximates c++ stl iterators for bytes where you get some tiny bit of hotspot love for a tight loop comparing values.
m

miha-x64

11/25/2019, 6:21 PM
I'd like to see Iterators instead of Sequences 🤔
d

Dominaezzz

11/25/2019, 6:25 PM
asIterator()
solves that.
m

miha-x64

11/25/2019, 7:11 PM
no-no-no, creating a redundant wrapper is a responsibility of a person who wants it:
.toSequence()
e

elizarov

11/25/2019, 7:22 PM
We try to avoid public APIs that return single-shot entities like
Iterator
. They are error-prone to work with. That is why Kotlin collections do not have any operators on iterators.
Sequence
is multi-use, thus easier to reason about, since it has not intrinsic “state” (used/not-used) that a person using it has to keep in mind.
m

miha-x64

11/25/2019, 7:46 PM
But
.constrainOnce()
makes `Sequence`s even more unsafe.
e

elizarov

11/25/2019, 8:08 PM
Yes. That is why I say “we try to”. There are some primitives that violate this rule, but they are limited. Same with
Flow
. Most of them multi-use with limited exceptions
View count: 2