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

    Hullaballoonatic

    11/29/2019, 5:57 PM
    fun <K, V> Array<K>.associateWith(valueSelector: (K) -> V): Map<K, V>
    why is this not in stdlib already? i'm very confused. all other versions of associate from
    Iterable
    exist on
    Array
    except this one. my use case:
    myEnumClass.values().associateWith { ... }
    i
    b
    m
    • 4
    • 10
  • h

    Hullaballoonatic

    12/04/2019, 5:07 PM
    Just as
    fold
    and
    reduce
    have
    foldRight
    ,
    reduceRight
    , I would like
    windowedRight
    and
    chunkedRight
    . My current use case is also maybe the best example:
    val Int.digitBlocks get() = toString().chunkedRight(3).map(String::toInt) // 1_234_567 -> [[567], [234], [1]]
    I noticed
    CharSequence
    also has a version of
    windowed
    that accepts a transform operation, and I would like that for
    Iterable
    as well. In general why don't most Iterable operations also have a version with a transform operation tacked on? I don't think that hurts readability, and only partially conflicts in places where the operation already receives a lambda, like
    partition
    z
    • 2
    • 4
  • l

    Leon K

    12/05/2019, 4:40 PM
    Proposal: I'd love to have versions of
    require
    that allow for specifying a custom Exception type to throw, instead of just throwing
    IllegalArgumentException
    k
    l
    • 3
    • 13
  • a

    asad.awadia

    12/05/2019, 8:39 PM
    Is there anything i can use that is like apply but doesn’t mutate the original object and instead returns a copy?
    r
    m
    • 3
    • 3
  • x

    Xavier F. Gouchet

    12/06/2019, 10:05 AM
    I have the following method that I used a bunch of times already, which could find it's place in the stdlib maybe :
    operator fun Char.times(i: Int): String {
        check(i >= 0) { "Can't repeat character negative times " }
        return String(CharArray(i) { this })
    }
    
    val s = '_' * 8
    👌 3
    d
    n
    • 3
    • 2
  • j

    jimn

    12/07/2019, 4:58 PM
    is this still currently accurate info?
    b
    • 2
    • 6
  • l

    LeoColman

    12/10/2019, 8:41 PM
    Why is there a
    String?.isNullOrBlank()
    but there is no
    String?.isNotNullOrBlank()
    while there is a
    String.isBlank()
    and
    String.isNotBlank()
    👆 1
    a
    s
    +3
    • 6
    • 9
  • s

    Simon Schubert

    12/12/2019, 12:06 PM
    I try to get the image url of the first object that exist in the database based on a list of object ids. My current solution looks like the following:
    var ids = listOf("123", "456", ...)
    var imageUrl = getFirstImageUrl(ids)
    
    fun getFirstImageUrl(list: List<String>): String? { 
        list.forEach {
           var item = database.getItemById(it)
           if(item != null) {
              return item.imageUrl
           }
        }
        return null
    }
    Is there a better way to do it in kotlin? I could image a solution something like this:
    var imageUrl = ids.firstNotNullFlat {
      var item = database.getItemById(it)
      item?.imageUrl
    }
    s
    p
    • 3
    • 7
  • l

    Leon K

    12/14/2019, 11:00 AM
    small stdlib proposals to improve smart-casting concerning nullability: we need a way to do
    if(foo != null)
    for multiple values and collection contents. Proposal part one add a
    ifNotNull
    function that takes vararg arguments of type
    Any?
    . given
    val a: Int? = 1
    val b: String? = null
    val c: Boolean? = false
    this would allow to replace this:
    if (a != null && b != null && c != null) {
        println("$a, $b, $c")
    }
    with this:
    ifNotNull(a, b, c) {
        println("$a, $b, $c")
    }
    which imo is a lot more readable, and also easier to type. (small note/question: would these checks - if the function was just implemented in terms of contracts and the if-statement - short-circuit, like they do with the if-statement?) proposal part two higher-order-functions on collections should do smart-casting. (I guess this should be doable via contracts?) given
    fun useList(nums: List<Int>) = println(nums)
    val foo: List<Int?> = listOf(12, 13, null, 14)
    this would allow to do something like this:
    if (foo.all { it != null } ) {
    	useList(foo)
    }
    currently, afaik, this check is not possible with compiler-guarantees, as there is no
    Collection<T>.hasNoNulls()
    check. there are some simmilar functions, but nothing that actually does this. there is -
    Iterable<T?>.requireNoNulls()
    - the most simmilar, but this throws exceptions and isn't as general as making
    all
    and
    any
    -calls smart-cast -
    Iterable<T?>.filterNotNull()
    - could be currently used in combination with the all-check to "simulate" a smart-casting all, but as it just filters out the null-values, this could to easily be broken if someone isn't careful when modifiying the preceding if-statement.
    k
    n
    • 3
    • 4
  • j

    jimn

    12/15/2019, 10:19 AM
    is
    "string".size
    unreasonable as a stdlib feature?
    t
    k
    +4
    • 7
    • 26
  • d

    dave08

    12/15/2019, 2:00 PM
    Any reason why there's no
    toTypedArray
    on a
    Sequence
    ?
    j
    m
    +2
    • 5
    • 43
  • s

    Sujit

    12/18/2019, 12:58 AM
    Looks like standard library issue that I've been chasing. I have a simple class with lots of members like this:
    class TooManyMembers(
            val mem1: Int? = null,
            val mem2: Int? = null,
            .
            .
            .
            val mem248: Int? = null) {
        }
    That's a class with 248 members. Instantiating this member with
    val obj = TooManyMembers()
    throws this error at runtime:
    Too many arguments in method signature in class file SerializationTests$TooManyMembers
    java.lang.ClassFormatError: Too many arguments in method signature in class file SerializationTests$TooManyMembers
    If I remove just one member, no more of that error. Is that really a limit (247) with numbers of members one can have in a kotlin class? What can I do if I have an object with more members? 247 seems way too low. This is with kotlin
    1.3.61
    j
    g
    +2
    • 5
    • 18
  • m

    Marc Knaup

    12/24/2019, 12:00 PM
    Wouldn’t it be nice if
    .toList()
    ,
    .map()
    ,
    .filter()
    ,
    listOf()
    , etc. use some immutable
    List
    subclass internally, so that subsequent calls to
    .toList()
    don’t have to create another copy? 🙂 Would be great for defensive copy patterns, since you don’t know whether the list you get is immutable or not.
    m
    • 2
    • 4
  • m

    Marc Knaup

    12/24/2019, 4:23 PM
    Why is
    Map.getOrElseNullable()
    not public API? I’ve just now noticed that
    .getOrElse()
    doesn’t work as documented for
    null
    values.
    Returns the value for the given key, or the result of the
    defaultValue
    function if there was no entry for the given key.
    ➕ 1
    m
    • 2
    • 14
  • j

    jimn

    01/05/2020, 8:44 AM
    I wrote a singular feature_range iterator to reduce potential memory paging events when working with potentially large datasets. minmax scaling is integral with tensorflow and similar domains. also related to what's shown here, doing index resampling on downstream tensorflow input. i have two three issues with this as presented: 1. I'm not sure how to best generalize the acc to a paramterized type:
    (LocalDate.MAX t2 LocalDate.MIN)
    except with some keyboard practice for each of the primitive types getting thier own minmax 2. related to existing keyboard practice: min and max don't want to behave in intellij with a generic syntax and it's hard to guess the intent of max`Of` vs. max, min`Of` vs. min -- since they both evaluate on pairs where list`Of` for instance operates on vararg<T> 3. i distrust an immutable loop return where an array of two mutable values might have more mechanical sympathy
    fun feature_range(seq: Sequence<LocalDate>):Pair</**min*/LocalDate,/**max*/LocalDate> = seq.fold(LocalDate.MAX to LocalDate.MIN) { (a, b), localDate ->
        minOf(a, localDate) to maxOf(b, localDate)
    }
    • 1
    • 2
  • g

    gregorbg

    01/08/2020, 7:06 PM
    What would be an idiomatic way to convert a
    Map<K, List<V>>
    into a
    Map<V, K>
    such that every entry in the
    List<V>
    becomes associated with its original key
    K
    ? (
    {"foo": [1, 2, 3]}
    becomes
    {1: "foo", 2: "foo", 3: "foo"}
    )
    d
    j
    • 3
    • 6
  • x

    Xavier F. Gouchet

    01/09/2020, 10:53 AM
    Hey not sure if that would add value to others, but it would be nice to have a
    clamp
    method on Numbers in the StdLib :
    fun clamp(d: Double, min : Double, max : Double) : Double {
        return if (d < min) {
            min
        } else if (d > max) {
            max
        } else {
            d
        }
    }
    or
    fun Double.clamp(min : Double, max : Double) : Double {
        return if (this< min) {
            min
        } else if (this > max) {
            max
        } else {
            this
        }
    }
    d
    n
    • 3
    • 2
  • z

    Zac Sweers

    01/10/2020, 7:59 AM
    Is it intentional that
    typeOf()
    for mutable collections just returns the immutable type?
    e
    • 2
    • 1
  • z

    Zac Sweers

    01/10/2020, 8:07 AM
    More here https://github.com/square/kotlinpoet/issues/279#issuecomment-522442378
    i
    • 2
    • 2
  • b

    bbaldino

    01/13/2020, 6:17 PM
    Is there a YT bug which tracks the removal of experimental status for
    typeOf
    ?
    m
    • 2
    • 2
  • a

    asad.awadia

    01/15/2020, 12:05 AM
    is there a way to generate a giant when clause - given a List of predicates?
    d
    d
    j
    • 4
    • 7
  • m

    Mark

    01/17/2020, 6:05 AM
    If I define a function in an
    inner class
    I can access it normally from outside of that class and containing class. But if I move that function out of inner class (but still inside the containing class) and make it an extension fun of the inner class, then I cannot access it in the same way - instead I need to do
    with(instanceOfContainingClass)
    Why the difference?
    m
    • 2
    • 14
  • g

    gcx11

    01/18/2020, 12:53 PM
    Hello, is there a better/more idiomatic way to write this function? I couldn't find anything like this in the standard library.
    inline fun <T, C: MutableCollection<T>> MutableList<T>.retrieveAllTo(collection: C, predicate: (T) -> Boolean): C {
        val iterator = this.listIterator()
    
        for (item in iterator) {
            if (predicate(item)) {
                collection.add(item)
                iterator.remove()
            }
        }
    
        return collection
    }
    
    inline fun <T> MutableList<T>.retrieveAll(predicate: (T) -> Boolean): List<T> {
        return mutableListOf<T>().also { retrieveAllTo(it, predicate) }
    }
    d
    g
    • 3
    • 2
  • k

    Kiryushin Andrey

    01/21/2020, 1:29 PM
    Hey all! I'm currently diving into Kotlin on JVM, coming from C# background, and I have some questions about iterables, sequences and streams, can anyone help me? My questions are the following • I understand the different intentions behind Iterable and Sequence implementations, however I still don't quite understand why two different interfaces with identical signatures are needed. In C# there is only one
    IEnumerable
    interface and its extension methods behave like the ones for
    Sequence
    - that is, they are evaluated lazily, processing items from the source one by one. Therefore in C# any LINQ method applied to a collection starts a chain of lazy methods operating on
    IEnumerable
    and we use
    ToList
    in the end if a materialized collection is needed as a result of the pipeline. In Kotlin, then, not only the lazy to eager transition should be done explicitly (by calling
    toList
    ) but also an eager to lazy one (by calling
    asSequence
    ). Is this explicitness the purpose of existing separate
    Sequence
    and
    Iterable
    interfaces? Why is this explicitness in going from eager to lazy evaluation needed? Or does it have something to do with the fact that
    Iterable
    comes from Java and has been therefore in some way not suitable for lazy evaluations? • I also had a glimpse of streams in Java. Am I right that conceptually this is the same as
    Sequence
    in Kotlin, so that
    Sequence
    should be used everywhere unless Java interop is required? Are there some advantages of streams over sequences or sequences over streams besides those imposed by the fact that one comes from Kotlin and the other from Java?
    r
    z
    e
    • 4
    • 4
  • w

    wasyl

    01/24/2020, 2:14 PM
    Hi all, is there any ticket or was there any discussion about adding Base64 encoding/decoding utilities to Kotlin’s standard library?
    m
    j
    c
    • 4
    • 3
  • a

    asad.awadia

    02/01/2020, 3:48 PM
    would there be a better way of just updating the count somehow
    c
    • 2
    • 3
  • j

    jimn

    02/07/2020, 5:53 AM
    i dismissed a notice of
    A.(B)->C
    when i came upon a random refactoring intent having reverted it after testing it and seeing it worked all the same. https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver as it turns out is a real thing. so there are a few quirks about stdlib, gaps between say list and array which appeear to be interchangable but are not(unless i write them). and likewise for the primitive arrays and the object arrays. is there an undercurrent of some java-generics like algebra that spoils it for writing a suite of generic extensions for the existing base kotlin libs?
    i
    r
    • 3
    • 6
  • m

    Marc Knaup

    02/07/2020, 7:36 AM
    .ifNull { … }
    would be awesome indeed :) https://kotlinlang.slack.com/archives/C0B8Q383C/p1481236430000013
    ?:
    requires weird brace positioning and makes functional code less readable.
    inline fun <T : Any> T?.ifNull(onNull: () -> T): T {
    	contract {
    		callsInPlace(onNull, InvocationKind.AT_MOST_ONCE)
    	}
    
    	return if (this !== null) this else onNull()
    }
    ➕ 5
    m
    • 2
    • 2
  • e

    elect

    02/07/2020, 7:45 AM
    there is a
    public fun <T> compareBy(vararg selectors: (T) -> Comparable<*>?): Comparator<T>
    but the descending counterpart is missing
    m
    • 2
    • 4
  • m

    Marc Knaup

    02/07/2020, 8:28 AM
    Are there any plans to make all number types (including unsigned ones) implement a shared interface? It’s odd to that unsigned numbers don’t implement
    kotlin.Number
    , which unfortunately is an abstract class.
    ➕ 1
    e
    z
    • 3
    • 2
Powered by Linen
Title
m

Marc Knaup

02/07/2020, 8:28 AM
Are there any plans to make all number types (including unsigned ones) implement a shared interface? It’s odd to that unsigned numbers don’t implement
kotlin.Number
, which unfortunately is an abstract class.
➕ 1
e

elect

02/07/2020, 1:43 PM
they should change that to
interface
if possible
z

Zach Klippenstein (he/him) [MOD]

02/07/2020, 3:23 PM
They don't implement a shared type on the jvm, and since kotlin interfaces map directly to java interfaces, the only way to do this would be using something like typeclasses (https://github.com/Kotlin/KEEP/pull/87)
View count: 2