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
announcements
  • b

    bod

    12/21/2020, 1:51 PM
    Hello, World! I want to enhance the
    toString
    of some class that belongs to a dependency. For that I'll make an extension, but can't call it
    toString
    for obvious reasons, and I'm not very inspired, can you think of a good name?
    betterToString()
    /
    toExtraNiceString
    /
    toEnhancedString
    /
    toDetailedString
    ... Better ideas? 🙏
    m
    n
    +2
    • 5
    • 5
  • s

    Scott Whitman

    12/21/2020, 3:27 PM
    What are the advantages/disadvantages of the atomicFu
    ReentrantLock.withLock {}
    vs. the coroutines
    Mutex.withLock {}
    ?
    s
    • 2
    • 2
  • n

    Nir

    12/21/2020, 5:23 PM
    It seems like there's still an outstanding issue in Kotlin, with regards to data classes with private constructors. The basic problem being that the copy method allows you to still set the members individually, and is always public, and cannot be deleted. This means that currently in Kotlin it doesn't really seem possible to write a data class in Kotlin that has any invariants amongst members which are part of its representation, which is annoying if you primarily want the data class for hashing or equality, for example. What's the recommended practice around this for now, and what direction is it headed in the future?
    j
    d
    j
    • 4
    • 11
  • d

    dmcg

    12/21/2020, 5:54 PM
    https://stackoverflow.com/questions/65397653/is-there-a-standard-kotlin-function-for-splitting-a-sequence-into-a-head-and-a-t
    n
    • 2
    • 14
  • ł

    Łukasz Bednarczyk

    12/21/2020, 7:15 PM
    Hi 🙂 is here anyone who knows spring? I need advice
    m
    • 2
    • 2
  • a

    andylamax

    12/22/2020, 1:46 AM
    I am getting error: The feature "unit conversion" is disabled. What does this mean? and how do I enable it? IDEA suggested to set languageVersion to "1.4", I am still getting the error though
    m
    • 2
    • 6
  • n

    Nir

    12/22/2020, 10:15 PM
    This is the stdlib implementation of MutableMap.getOrPut
    public inline fun <K, V> MutableMap<K, V>.getOrPut(key: K, defaultValue: () -> V): V {
        val value = get(key)
        return if (value == null) {
            val answer = defaultValue()
            put(key, answer)
            answer
        } else {
            value
        }
    }
    It seems like either the implementation or the description is wrong:
    Returns the value for the given key. If the key is not found in the map, calls the defaultValue function, puts its result into the map under the given key and returns it.
    println(mutableMapOf<Int, Int?>(5 to null).getOrPut(5) { 10 })
    Prints 10. However, 5 is "in the map" (
    println(5 in mutableMapOf<Int, Int?>(5 to null)
    prints true). kotlin nulls are very tricky in generic code.
    m
    • 2
    • 5
  • d

    df

    12/23/2020, 12:22 PM
    why is transform in Map.mapValues defined as
    transform: (Map.Entry<K, V>) -> R
    instead of just
    transform: (V) -> R
    ?
    v
    d
    n
    • 4
    • 11
  • r

    Robert Jaros

    12/23/2020, 2:31 PM
    Can we use current versions of coroutines and serialization with 1.4.30-M1?
    l
    • 2
    • 1
  • e

    Eric Lekwa

    12/23/2020, 4:46 PM
    Hey guys currently out of a Job 😩, but good news is I am willing to volunteer with any who needs help on a project 🙏.
    a
    v
    m
    • 4
    • 3
  • z

    zain

    12/24/2020, 7:03 AM
    Hey what does the colors signify in IDE for example Android Studio: For yellow and white over here
    t
    a
    • 3
    • 4
  • h

    hisham bin awiad

    12/24/2020, 8:01 AM
    Hello every one can anyone help me with How to get list of videos from specific folder in android ?
    k
    • 2
    • 1
  • a

    Alexandru Hadăr

    12/24/2020, 8:12 AM
    In the coroutines documentation, it's stated about
    join
    (link) that if called on a coroutine that's cancelled, it will throw an
    CancellationException
    . However, in this example from the official docs,
    job.join()
    is called right after
    job.cancel
    , yet it does not throw anything. Why not ?
    g
    • 2
    • 3
  • l

    lawlorslaw

    12/24/2020, 3:40 PM
    Is there a better name for a class that has these properties?
    Untitled
    s
    j
    j
    • 4
    • 7
  • m

    melatonina

    12/24/2020, 5:45 PM
    Hello. Are there
    StateFlow
    builders similar to
    callbackFlow
    ? I'm trying to transform this code to use a
    StateFlow
    instead of a `Flow`:
    fun <T> ObservableValue<T>.values(): Flow<T> = callbackFlow {
        val listener = javafx.beans.value.ChangeListener<T> { _, _, newValue ->
            offer(newValue)
        }
    
        addListener(listener)
    
        awaitClose { removeListener(listener) }
    }
    f
    n
    • 3
    • 7
  • e

    Edoardo Luppi

    12/24/2020, 6:07 PM
    I'm trying to import the atomicfu plugin using Gradle, but the dependency is unresolved. Do I need a particular repository?
    t
    • 2
    • 9
  • h

    Hamza GATTAL

    12/24/2020, 8:12 PM
    Hi everyone The wibinar of today is not available in the YouTube channel what's happened
    j
    d
    • 3
    • 4
  • c

    CircuitRCAY

    12/25/2020, 1:37 AM
    Would union types in Kotlin, instead of overloads be possible in the future?
    r
    n
    • 3
    • 3
  • c

    CircuitRCAY

    12/25/2020, 1:40 AM
    an example of union types in kotlin would be
    fun union(message: String | ByteArray)
    f
    • 2
    • 1
  • a

    Andrew

    12/25/2020, 3:19 AM
    May not be specific to kotlin but I am trying to add some unit tests that run independent of regular tests, ideally the "test" gradle task would skip these but another task would run only those. How can I do this aside from adding another project just for testing?
    a
    v
    • 3
    • 3
  • k

    kartikpatodi

    12/25/2020, 7:29 AM
    How do I add multiple -Xopt-in flags in gradle?
    v
    a
    • 3
    • 4
  • e

    Esa

    12/25/2020, 9:07 PM
    Hi, I'm experiencing an issue with the official code style in IntelliJ. Some times it seems to override my preferred code style with this one. And the two styles are quite different, so it is very jarring when it happens. Is there any foolproof way to make sure it does not randomly revert back to the stock code style?
    m
    • 2
    • 1
  • b

    buszi0809

    12/26/2020, 7:25 PM
    Hi, I'm looking for a good explanation of cold and hot Flows in Kotlin, i feel like I don't really understand the concept and implementation from the ones I've found, can anyone provide good one?
    m
    • 2
    • 3
  • a

    Ahmed Mourad

    12/27/2020, 12:14 PM
    For a class `X`:
    data class X(val v: String)
    If this works
    X::v
    shouldn't this also work
    X?::v
    ?
    h
    c
    n
    • 4
    • 29
  • h

    hisham bin awiad

    12/27/2020, 4:43 PM
    how can show list of videos by
    kotlin
    any one faced this before Plz help me
    ❓ 4
    m
    • 2
    • 5
  • p

    Poohrang

    12/27/2020, 5:01 PM
    Is there channel related with exposed for database?
    🤦 1
    m
    • 2
    • 2
  • c

    caelum19

    12/27/2020, 10:07 PM
    I've an
    object
    that is quite useful to access statically and dynamically. It has some nested properties and classes, and I am currently serializing it with kotlinx.serialization to save it when the application closes. However for loading, Kotlin does not allow me to assign the object with =, is there a way to assign it anyway or another way to do this? The object again has nested objects inside it, so manually setting each property is a solution I would rather avoid 🙂
    n
    f
    s
    • 4
    • 15
  • p

    Peter Ertl

    12/28/2020, 3:35 PM
    what would be the proper way with kotlin coroutines to signal events (like wait / notify in java)?
    d
    j
    • 3
    • 12
  • a

    Animesh Sahu

    12/29/2020, 3:56 AM
    Not really specific to Kotlin, but to JVM (and indirectly linked :p). Can somebody help? https://stackoverflow.com/q/65486924/11377112
    • 1
    • 1
  • m

    Mark Fisher

    12/29/2020, 10:21 AM
    Hi Kotliners, A post xmas question for anyone alive in this time of limbo before the new year! I've got a generics question. I can't understand why there's an error in the following:
    interface HexData
    object EmptyHexData : HexData
    data class Hex(val q: Int, val r: Int, val s: Int)
    
    interface HexDataStorage<T: HexData> {
        fun addHex(hex: Hex)
        fun addHex(hex: Hex, data: T): Boolean
    }
    
    class DefaultHexDataStorage<T: HexData> : HexDataStorage<T> {
        private val storage = LinkedHashMap<Hex, T>()
    
        override fun addHex(hex: Hex) {
            storage[hex] = EmptyHexData // <-- ERROR
        }
    
        override fun addHex(hex: Hex, data: T): Boolean {
            val previous = storage.put(hex, data)
            return previous != null
        }
    }
    In the function addHex(hex: Hex), I cannot use "EmptyHexData", and I don't understand why. AFAIU It's a sub-type of HexData, so I thought it would comply with the requirement of being a
    T
    in this case. What's wrong, and how do I fix it? I tried using a class too, e.g.
    class EmptyHexDataClass: HexData
    but that didn't work either.
    g
    y
    +4
    • 7
    • 25
Powered by Linen
Title
m

Mark Fisher

12/29/2020, 10:21 AM
Hi Kotliners, A post xmas question for anyone alive in this time of limbo before the new year! I've got a generics question. I can't understand why there's an error in the following:
interface HexData
object EmptyHexData : HexData
data class Hex(val q: Int, val r: Int, val s: Int)

interface HexDataStorage<T: HexData> {
    fun addHex(hex: Hex)
    fun addHex(hex: Hex, data: T): Boolean
}

class DefaultHexDataStorage<T: HexData> : HexDataStorage<T> {
    private val storage = LinkedHashMap<Hex, T>()

    override fun addHex(hex: Hex) {
        storage[hex] = EmptyHexData // <-- ERROR
    }

    override fun addHex(hex: Hex, data: T): Boolean {
        val previous = storage.put(hex, data)
        return previous != null
    }
}
In the function addHex(hex: Hex), I cannot use "EmptyHexData", and I don't understand why. AFAIU It's a sub-type of HexData, so I thought it would comply with the requirement of being a
T
in this case. What's wrong, and how do I fix it? I tried using a class too, e.g.
class EmptyHexDataClass: HexData
but that didn't work either.
g

Giorgos Neokleous

12/29/2020, 10:32 AM
Do you need generics at all in your example? Seems like you can just get by without them
interface HexDataStorage {
    fun addHex(hex: Hex)
    fun addHex(hex: Hex, data: HexData): Boolean
}
class DefaultHexDataStorage : HexDataStorage {
    private val storage = LinkedHashMap<Hex, HexData>()
    override fun addHex(hex: Hex) {
        storage[hex] = EmptyHexData
    }
    override fun addHex(hex: Hex, data: HexData): Boolean {
        val previous = storage.put(hex, data)
        return previous != null
    }
}
y

Yev Kanivets

12/29/2020, 10:33 AM
addHex(hex: Hex)
takes
Hex
, not
T
, and
EmptyHexData
doesn’t inherit from
Hex
, but from
HexData
.
😅 1
👎 2
v

Vampire

12/29/2020, 10:34 AM
@Yev Kanivets I think you misread the example
m

Mark Fisher

12/29/2020, 10:34 AM
@Yev Kanivets that's not right here, the type is in the storage.
v

Vampire

12/29/2020, 10:35 AM
@Mark Fisher
T
is
HexData
or a subtype of it
So if you have
interface MyHexData : HexData
and then have a
DefaultHexDataStorage<MyHexData>
that would be legal
But then you couldn't assign
EmptyHexData
as it is a
HexData
, but not a
MyHexData
That's why it says "you have
EmptyHexData
but
T
was expected"
m

Mark Fisher

12/29/2020, 10:37 AM
@Giorgos Neokleous I did consider a non-generics version, and instead have a Maybe<T> there, but still would like to get this working without the Maybe class which I think adds noise. @Vampire isn't EmptyHexData a subtype of HexData?
v

Vampire

12/29/2020, 10:37 AM
So it's back to the question of Girogos, why generics at all
Of course it is, but not of
MyHexData
as I just explained
If you create a
DefaultHexDataStorage<MyHexData>
your map will have runtime type
LinkedHashMap<Hex, MyHexData>
and
EmptyHexData
is not a
MyHexData
but a sibling
m

Mark Fisher

12/29/2020, 10:39 AM
ah, that explains it better, when considering the actual implementation, i need a full type.
v

Vampire

12/29/2020, 10:40 AM
So again the question of Giorgos, why do you need generics at all? Or a
Maybe
whatever that should be.
Why wouldn't his suggestion work for you?
m

Mark Fisher

12/29/2020, 10:41 AM
It is good enough to not use Generics, but I couldn't understand why the posted version wasn't working. You've explained that well enough now for me to understand, so thanks! 🙂
👌 1
r

Rob Elliot

12/29/2020, 11:11 AM
In terms of what you’re trying to achieve with the generic type, you’re probably better off using
null
to represent `EmptyHexData`:
private val storage = LinkedHashMap<Hex, T?>()
    override fun addHex(hex: Hex) {
        storage[hex] = null
    }
m

Mark Fisher

12/29/2020, 2:52 PM
@Rob Elliot That's why I used Maybe<T>, to avoid the use of nulls:
private val storage = LinkedHashMap<Hex, Maybe<T>>()

    override fun addHex(hex: Hex) {
        storage[hex] = Maybe.empty()
    }

    override fun addHex(hex: Hex, data: T): Boolean {
        val previous = storage.put(hex, Maybe.of(data))
        return previous != null
    }
Although my current implementation doesn't need generics, so I've stripped it back to simple HexData types directly.
v

Vampire

12/29/2020, 2:56 PM
And where is the advantage to wrap the entries instead of using a nullable type?
m

Mark Fisher

12/29/2020, 2:58 PM
I'm averse to using nulls and nullable types.
y

Youssef Shoaib [MOD]

12/29/2020, 3:37 PM
Using null and nullable types is idiomatic in Kotlin instead of using a maybe since the language has complete support for it. This isn't only my opinion, but also the opinion of actual fp experts like the whole Arrow team who decided to deprecate Maybe in favour of the native Kotlin nullables since the compiler tracks the nullable types and checks any calls that you try to do on them automatically (similar to how they decided to go with suspend instead of an
IO
wrapper since the compiler automatically tracks effects with suspend)
n

Nir

12/29/2020, 3:40 PM
I'd agree that nullable types are idiomatic in Kotlin broadly speaking but nullables can be a bit of a pain in generic contexts
and in particular Map<Hex, HexData?> can be pretty annoying
a lot of the extension functions for Map (and MutableMap) don't do what you'd expect, and basically act as though an entry to null isn't actually in the map
I actually agree with the approach here, it leads to less confusing code
View count: 1