https://kotlinlang.org logo
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
benchmarks
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
confetti
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
lincheck
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
Title
d

Dan T

05/29/2019, 8:25 PM
Question on combining sealed classes with data classes, in thread.
sealed class Animal {
    abstract val weight: Int
}

data class Dog(
    override val weight: Int,
    private val barkSound: String
) : Animal()

data class Cat(
    override val weight: Int,
    private val meowSound: String
) : Animal()


fun main() {
    val dog : Animal = Dog(weight = 1, barkSound = "woof")
    
    // what's the most elegant way to allow the following?
    val heavierDog = dog.copy(weight = weight + 1) 
}
so far this is the cleanest way i can find. if there's something better, please let me know:
sealed class Animal {
    abstract val weight: Int
    abstract fun copy(
        weight: Int = this.weight
    ): Animal
}

data class Dog(
    override val weight: Int,
    private val barkSound: String
) : Animal() {
    override fun copy(weight: Int): Animal {
        return copy(weight = weight, barkSound = this.barkSound)
    }
}

data class Cat(
    override val weight: Int,
    private val meowSound: String
) : Animal() {
    override fun copy(weight: Int): Animal {
        return copy(weight = weight, meowSound = this.meowSound)
    }
}


fun main() {
    val dog : Animal = Dog(weight = 1, barkSound = "woof")
    val heavierDog = dog.copy(weight = 2)
    println(heavierDog)
}
k

karelpeeters

05/29/2019, 8:37 PM
I think that's about the best you're going to get.
d

Dan T

05/29/2019, 8:52 PM
thanks. in converting from my simple example to my real code i discovered another hiccup. If a subtype of the sealed class doesn't add any additional properties, it results in a compilation issue due to the generated copy function being a duplicate of the sealed class. e.g.
sealed class Animal {
    abstract val weight: Int
    abstract fun copy(
        weight: Int = this.weight
    ): Animal
}

data class BasicAnimal(
    override val weight: Int
) : Animal()
k

karelpeeters

05/29/2019, 8:52 PM
Name it
clone
😒imple_smile:
d

Dan T

05/29/2019, 8:53 PM
results in
Function 'copy' generated for the data class has default values for parameters, and conflicts with member of supertype 'Animal'
so far the best i can think of for that situation is to add in an unused/ignored property. vestigial animal tail 🙂
k

karelpeeters

05/29/2019, 8:55 PM
As you've noticed data classes and inheritance don't play that well together. I think the
copy
function for data classes was a mistake.
d

Dan T

05/29/2019, 9:07 PM
😕 yeah they don't. thanks for the tips
s

streetsofboston

05/29/2019, 9:59 PM
This is likely overkill, but the ‘Lensing’ of functional programming could help 🙂 : https://arrow-kt.io/docs/optics/lens/#composition Not sure if the lensing module of Arrow works for non-data classes, though….
👍 1
g

gildor

05/29/2019, 11:31 PM
Why copy is a mistake? Do you have better solution? Because it would be very verbose to use immutable data classes
k

karelpeeters

05/29/2019, 11:39 PM
Couple of things: • This might just be me, but I very rarely use them, I can't actually remember the last time and I searched my recently opened projects, nothing. • Clashes with other functions named
copy
• "Private data class constructor is exposed via the generated
copy
method", this basically makes private data class constructors useless.
g

gildor

05/29/2019, 11:55 PM
1. Than you never modify them, which of course possible in some use cases, but when you need it it's becoming huge problem, especially for classis with a lot of properties, and I just wouldn't use data classes if there wouldn't be
copy
and keep using AutoValue or similar solution 2. Not really a big problem, imo, but would be nice to fix 3. I agree that it is unfortunate, would be nice to have a way to make copy private or disable it
k

karelpeeters

05/30/2019, 12:05 AM
Interesting, I'll be on the lookout for a copy use-case in the future. Most of my data classes are really small, 2-3 properties so maybe that's why. I'd still be happy with a way to disable them though.
I guess I meant to say that copy being there by default is weird,
hashcode
and
equals
make sense,
component
a bit less and
copy
even less. Some modularity would be nice but then that's more syntax. It's a balance 😒imple_smile:
g

gildor

05/30/2019, 12:40 AM
I wouldn't say it's weird, it's just has another use case in mind, that it's pure data so it doesn't expose implementation details etc
d

Dico

05/30/2019, 2:18 AM
It's a class to hold data, it makes perfect sense to me that the data can be copied. What gives? I don't hse it that often but it's definitely convenient at times
k

karelpeeters

05/30/2019, 8:58 AM
Especially the private constructor thing is annoying, the copy function just breaks it and there's nothing you can do about it.
g

gildor

05/30/2019, 9:33 AM
which is also considered by many as incorrect usage of pure data class (to have data validation on constuctor)
k

karelpeeters

05/30/2019, 10:33 AM
Maybe, but my common use case is that I just want
equals
and
hashcode
to be generated.
d

Dico

05/30/2019, 1:40 PM
Does it not make sense for a copy function to exist for a class that has equals and hash code generated based on its properties?
k

karelpeeters

05/30/2019, 1:41 PM
No, sometimes I want equals and hashcode but not a public constructor.
d

Dico

05/30/2019, 1:43 PM
That's fair
Would you be happy with an annotation that disables the generation of the copy function?
k

karelpeeters

05/30/2019, 1:44 PM
Yes that would be perfect.
d

Dico

05/30/2019, 1:44 PM
Or maybe it can be disabled for data classes with a private constructor, but that may be problematic
k

karelpeeters

05/30/2019, 1:45 PM
That would be a breaking change, there may be code out there that actually uses copy to work around a private constructor.
But in hindsight that would have been a good idea.
e

earroyoron

05/31/2019, 9:21 PM
copy
is perfect for
data class
as a data class is something you should not extend. Don’t worry to duplicate properties in two `data class`es as this is just where DRY is not applicable
1