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
hiring-french
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
m

Marcin Wisniowski

11/22/2021, 2:41 PM
Is there a way to avoid object instantiation for a simple class like
data class Point(val x: Int, val y: Int)
? In an API with lots of operations on such `Point`s, there is lots of
Point
objects being created. Changing the API to operate on x and y parameters separately without a
Point
class avoids the overhead, but makes the API less clean. Is there some language feature that can help here? I am looking for something like inline classes, but for two member properties.
j

Joffrey

11/22/2021, 2:44 PM
Value classes for multiple properties are not supported yet. In your specific case, you could work around it if you know the full dimension of the grid (and if it fits) by using a 1-dimensional index to represent the position in the 2D grid. EDIT: you could also just store these 2
Int
in the low and high bits of a
Long
, which doesn't require knowing the max width
Something like this for instance :
const val GRID_WIDTH = 200 // or whatever is your grid size

value class Point(private val index: Int) {
    val x: Int get() = index % GRID_WIDTH
    val y: Int get() = index / GRID_WIDTH
}
m

Marcin Wisniowski

11/22/2021, 2:46 PM
Although I used
Int
in my example for simplicity, my
Point
actually takes
Double
coordinates. So I cannot do such an operation.
Maybe I can find another way to fit two
Double
values into a single variable somehow.
j

Joffrey

11/22/2021, 2:48 PM
Although I used 
Int
 in my example for simplicity, my 
Point
 actually takes 
Double
 coordinates. So I cannot do such an operation.
And here goes the workaround.. out the window 😄
This workaround only works with int, where you can enumerate accurately those possibilities "row by row", but I'm not sure you can do something equivalent with doubles. Did you measure the impact of the extra
Point
objects though?
m

Marcin Wisniowski

11/22/2021, 2:53 PM
It's used during animations of multiple objects, there could be hundreds of
Point
objects created every frame. (But even if there was no impact this would be interesting to solve)
j

Joffrey

11/22/2021, 2:56 PM
It's used during animations of multiple objects, there could be hundreds of 
Point
 objects created every frame
Still doesn't mean it's a problem. It really depends on how you use these objects (what their lifecycle is). For instance, if you use them as temporary local variables, they will be allocated on the TLAB and will be very cheap
But even if there was no impact this would be interesting to solve
I think multi-property value classes will come at some point (so the Kotlin team is already working on it). This will be especially true when project Valhalla comes in. In the mean time, we're stuck with regular classes or workarounds that manage to cram everything in a single field 😄 of course you can also pass the 2 values as argument to all functions, but that doesn't solve the problem for return values
m

Michael Böiers

11/22/2021, 3:29 PM
Are you sure that the instantiation will be a performance problem? Modern VMs are pretty good at reusing small objects like that.
Of course you could create them all through a factory method and add some sort of cache in there, either caching all the points or just the most recently used.
But in essence, like I said in the previous comment, the VM is already doing something like that for all objects. My advice would be to go ahead with the data class and then, if performance becomes an issue, profile the application.
m

Marcin Wisniowski

11/22/2021, 4:39 PM
@Michael Böiers You are right, this is not a real issue but I was interested in the problem itself.
I managed to make a
Point(x: Double, y: Double)
value class. See it at your own risk: https://pl.kotl.in/camTTpjz5
😆 1
j

Joffrey

11/22/2021, 4:55 PM
Btw I realized my initial solution could have just been storing the two ints in the high and low bits of a single long (without even knowing the grid size and using
%
and
/
)
I managed to make a 
Point(x: Double, y: Double)
 value class
Now the question is: aren't all those operations actually slower than just allocating and garbage-collecting
Point
instances?
m

Michael Böiers

11/22/2021, 5:28 PM
Only a profiler can give you that answer.
👍 2
m

Marcin Wisniowski

11/22/2021, 5:31 PM
I'm not actually going to use it, but it was fun to implement.
I think multi-property value classes will come at some point
@Joffrey Is there a KEEP for that?
m

Michael Böiers

11/22/2021, 5:32 PM
You can still try it later, I like that it‘s fully compatible with the straight-forward implementation.
j

Joffrey

11/22/2021, 5:35 PM
There is this issue to track it: https://youtrack.jetbrains.com/issue/KT-1179 The initial KEEP for value classes also contains some information. You can start from this section: https://github.com/Kotlin/KEEP/blob/master/notes/value-classes.md#compiling-value-classes-the-single-field-restriction And carry on to the Valhalla part and the actual section about multiple fields just below.
👍 1
e

ephemient

11/22/2021, 10:57 PM
you can mux two Float into one Long, e.g.
value class FloatPair
generated by https://github.com/ephemient/kotlin-numeric but unfortunately Double is 64-bits and there is no 128-bit primitive so you can't pull the same trick
IMO Float is much more reasonable than "double with limited precision" that you wrote there
1
m

Marcin Wisniowski

11/23/2021, 12:32 AM
https://androidx.tech/artifacts/compose.ui/ui-geometry/1.0.0-beta02-source/androidx/compose/ui/geometry/Offset.kt.html I just found this while working on something unrelated, looks like what I did (except better). Maybe I wasn't so crazy after all.
e

ephemient

11/23/2021, 12:49 AM
https://github.com/androidx/androidx/blob/androidx-main/compose/ui/ui-util/src/commonMain/kotlin/androidx/compose/ui/util/InlineClassHelper.kt packFloats and unpackFloat[12] do the same thing I do in FloatPair, which is to use the raw bit representation of the Float
❤️ 1
what you have with Point is some sort of self-invented floating point format but with decimal base and less precision…