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

    chalup

    04/27/2017, 6:04 AM
    Can you spot the mistake:
    fun foo(key: Bar) = cache.getOrPut(key) { return somethingSomething(key) }
    y
    • 2
    • 2
  • j

    jw

    05/12/2017, 1:26 AM
    ah well that's good to know that's there, but i'm looking for an equivalent of
    isName
    specifically which determines whether or not a string is a keyword in the language
    u
    • 2
    • 1
  • v

    voddan

    05/22/2017, 6:22 PM
    Looking for a workaround my first idea was a
    Sequence
    function like
    File.readLinesInSequence(): Sequence<String>
    . Is it possible to implement it?
    i
    • 2
    • 3
  • j

    jw

    05/27/2017, 3:38 AM
    perhaps because it's declared
    @InlineOnly
    ?
    v
    • 2
    • 1
  • m

    miha-x64

    05/28/2017, 3:10 PM
    infix fun Int.has(flag: Int) = this and flag == flag
    infix fun Int.flagIf(condition: Boolean) = if (condition) this else 0
    Haven't I reinvented a bicycle (or a wheel)? Or there's something similar in stdlib?
    👍 1
    l
    t
    k
    • 4
    • 11
  • i

    ilya.gorbunov

    05/31/2017, 6:55 PM
    📣 For those who've tried Kotlin immutable collections and struggled with the operator importing we're going to suggest the following rather drastic solution: https://github.com/Kotlin/kotlinx.collections.immutable/issues/10#issuecomment-305277264 TLDR: We propose not to extend the immutable collections from read-only ones to mitigate this issue. If you have any objections or notes, please share them in that issue comments.
    😱 1
    🍻 1
    👍 5
    m
    • 2
    • 1
  • m

    mg6maciej

    06/02/2017, 10:09 AM
    Was
    Iterable<BigDecimal / BigInteger>.sum()
    ever considered?
    i
    • 2
    • 1
  • m

    mg6maciej

    06/02/2017, 10:11 AM
    And more generally these kind of holes in #stdlib where we have
    Iterable<Long>.sum()
    , but not
    List<*>.sumByLong
    (like we have
    sumBy
    for ints and
    sumByDouble
    ).
    i
    • 2
    • 2
  • m

    mg6maciej

    06/02/2017, 11:25 AM
    Double.doubleToLongBits
    /
    Double.longBitsToDouble
    😕
    😨 2
    d
    • 2
    • 2
  • v

    voddan

    06/03/2017, 3:17 PM
    +
    on
    Iterable
    is not it since it returns a list
    m
    • 2
    • 5
  • m

    marcinmoskala

    06/19/2017, 1:40 PM
    true
    • 1
    • 1
  • m

    marcinmoskala

    06/19/2017, 3:10 PM
    I prefer extensions over top-level functions because they are not suggested everywhere
    i
    • 2
    • 2
  • i

    ilya.gorbunov

    06/22/2017, 12:39 PM
    @natpryce Please submit your use cases to https://youtrack.jetbrains.com/issue/KT-17261, so we could know which part of its API should be exposed to multiplatform stdlib.
    n
    • 2
    • 3
  • m

    miha-x64

    06/23/2017, 10:04 AM
    Is there anything shorter than
    Collections.unmodifiableList(someArray.toList())
    ?
    l
    m
    • 3
    • 2
  • p

    pavlospt

    06/26/2017, 9:30 AM
    hello, so i was trying to find a more elegant way to write the following:
    selectedChoices.mapIndexed { index, isSelected -> if (isSelected) index else -1 }.filter { it != -1 }
    . Is there a prettier way to write this ? 🙂 In short what I want to do is get the indexes from
    selectedChoices
    , which is a BooleanArray, where the value is
    true
    and then map those indexes in something different, hence the
    .filter { it != -1}
    (also not sure if I am on the right channel)
    m
    • 2
    • 2
  • g

    gildor

    06/30/2017, 2:02 AM
    or more explicit and less cryptic:
    listOf(2, 3, 4).flatMap { item ->
            if (item % 2 == 0) {
                List(2) { if (it == 0) item else -item }
            } else {
                listOf(item)
            }
        }
    i
    m
    • 3
    • 3
  • v

    voddan

    07/03/2017, 4:19 PM
    Hm?
    Pair
    is not an optimization of
    Triple
    , they have different semantics. In addition, "pairwise" is unique in how obscure a naming it is
    i
    • 2
    • 2
  • b

    brk

    07/07/2017, 8:09 AM
    we already have nice
    to<Type>OrNull()
    string extensions https://github.com/Kotlin/KEEP/blob/master/proposals/stdlib/string-to-number.md But don't you think it would a good idea to add generalized version of 'try-or-null' to stdlib? like:
    val date = tryOrNull { myAwesomeDateTimeParser.parse("2017-13-32") }
    which is equal to:
    val date = try { myAwesomeDateTimeParser.parse("2017-13-32") } catch(e: Exception) { null }
    👍 1
    v
    • 2
    • 8
  • p

    pavlospt

    08/08/2017, 7:44 AM
    Does anyone know the reasoning behind this commit and the changes it introduced? https://github.com/JetBrains/kotlin/commit/5773594412660af11357ac9adc6ffcb45138b840
    e
    i
    v
    • 4
    • 10
  • d

    dmcg

    08/10/2017, 2:05 PM
    I wonder if we can summon @elizarov?
    e
    • 2
    • 1
  • j

    jw

    08/10/2017, 11:17 PM
    can
    @Throws
    be renamed
    @JvmThrows
    and a
    @Deprecated typealias
    be added to map it back to
    Throws
    ?
    :youtrack: 1
    👍 2
    • 1
    • 1
  • v

    voddan

    08/11/2017, 7:05 AM
    What if Kotlin compiles to a platform which makes use of exception lists in function declarations? I think it is a pretty generic thing
    o
    • 2
    • 1
  • d

    dmcg

    08/21/2017, 1:28 PM
    @elizarov re Result type. It wasn't that it didn't open, just that I expected some sort of Algebraic data type, sealed class hierarchy.
    e
    n
    +2
    • 5
    • 21
  • k

    karelpeeters

    08/28/2017, 9:38 AM
    What about
    val items = ingredentsList.flatMap { listOf(ListItem.HeaderItem(it.type), ListItem.IngredientItem(it)) }
    ?
    HeaderItem
    will need a correctly implemented `equals`/`hascode` for this.
    l
    i
    • 3
    • 10
  • b

    beholder

    08/31/2017, 2:55 PM
    Is it possible to compiler choose
    AutoClosable.use()
    instead of
    Closable.use()
    when class implements both interfaces? Implementation for AutoClosable is more simple and efficient.
    k
    • 2
    • 3
  • d

    ddsoyka

    08/31/2017, 5:20 PM
    is it safe to call
    assertEquals(byteArray, otherByteArray)
    and receive the expected result? Or do I need to call
    Arrays.equals()
    instead?
    i
    • 2
    • 4
  • d

    ddsoyka

    08/31/2017, 5:38 PM
    @jw Looks like someone already filed for it (https://github.com/kotlintest/kotlintest/issues/116)... maybe it's already in there?
    e
    • 2
    • 3
  • e

    elect

    09/03/2017, 2:16 PM
    https://github.com/kotlin-graphics/uno-sdk/blob/master/src/main/kotlin/uno/kotlin/buffers/intBuffer.kt
    b
    • 2
    • 2
  • k

    karelpeeters

    09/08/2017, 9:20 AM
    myMap.mapValuesTo(myMap) { ... }
    might work, never tried it before.
    m
    • 2
    • 5
  • d

    dimsuz

    09/08/2017, 9:20 AM
    For now I did a simple:
    inline fun <K, V> MutableMap<K,V>.replaceOrPut(key: K, updateOp: (V?) -> V): MutableMap<K, V> {
      val current = this[key]
      this[key] = updateOp(current)
      return this
    }
    n
    • 2
    • 1
Powered by Linen
Title
d

dimsuz

09/08/2017, 9:20 AM
For now I did a simple:
inline fun <K, V> MutableMap<K,V>.replaceOrPut(key: K, updateOp: (V?) -> V): MutableMap<K, V> {
  val current = this[key]
  this[key] = updateOp(current)
  return this
}
n

Nir

12/01/2020, 9:26 PM
Is there any chance of getting something like this in the standard library? Context:
inline fun <K, V> MutableMap<K,V>.replaceOrPut(key: K, updateOp: (V?) -> V): MutableMap<K, V> {
  val current = this[key]
  this[key] = updateOp(current)
  return this
}
I prefer to call this function update personally but the idea is the same. It's very useful. Without this I've found it's rather awkward to do certain things in Kotlin; updating for example integers in MutableMap<*, Int> is annoying, you can't even do
m["hello"] += 1
This is quite similar to Java hashmaps compute function: https://www.geeksforgeeks.org/hashmap-compute-method-in-java-with-examples/ which is absent in Kotlin's stdlib. Note that Python and C++ to take two examples, allow compound arithmetic on their mutable Maps, so this is fairly awkward relative to quite a number of existing mainstream languages
View count: 2