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
a

Andrew Hughes

08/23/2022, 4:54 PM
I noticed that the M3
ColorScheme
is annotated with
@Stable
, however, it does not override
equals
. The
@Stable
annotation mentions that the following must be true:
1. The result of
equals
will always return the same result for the same two instances.
I assume this means that two instances of a class with the same internal values should evaluate to
true
using
equals
. However, this is not the case for
ColorScheme
. Am I misunderstanding what this means?
m

MR3Y

08/23/2022, 5:26 PM
I assume this means that two instances of a class with the same internal values should evaluate to
true
using
equals
.
No, this is not what the documentation of
@Stable
is meaning. what it actually means is that calling
equals
on the same two instances should always return the same result even if that result was
false
, that doesn't violate stable contract. Also, see: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1660409798793859?thread_ts=1660409095.230819&cid=CJLTWPH7S
So, here
ColorScheme
isn't overriding
equals
, so, it will fallback to the default
equals
that is always returning
false
. That being said,
ColorScheme
complies with
@Stable
contract
a

Andrew Hughes

08/23/2022, 5:39 PM
Ah, okay that makes sense. Thanks!
What about annotating a function with
@Stable
? The documentation states:
When applied to a function or a property, the
Stable
annotation indicates that the function will return the same result if the same parameters are passed in. This is only meaningful if the parameters and results are themselves
Stable
,
Immutable
, or primitive.
If I have a function that returns an instance of a class that is marked
@Stable
, does that function need to return the exact same instance if the same parameters are passed in? Or can it return a different instance that is functionally equivalent?
m

MR3Y

08/23/2022, 8:13 PM
As long as those 2 instances don't violate
@Stable
contract, then the function can be stable.
a

Andrew Hughes

08/23/2022, 8:21 PM
I guess I'm still not following what they mean by "the function will return the same result if the same parameters are passed in". If I pass in an
@Stable
instance
A
as a parameter to a function and it returns an
@Stable
instance
B
. Does annotating the function with
@Stable
require that the instance
B
be returned every time
A
is passed in? Or could it return a different instance (
C
,
D
, ...) each time it is called with
A
, as long as the the returned value is "the same" (not necessarily
equal
or the same instance)?
And what if
A
is mutated (while complying with the
@Stable
contract)? In my scenario, this could change the output of the function. The question is, how does that affect the stability of the function?
m

MR3Y

08/23/2022, 8:44 PM
If I pass in an
@Stable
instance
A
as a parameter to a function and it returns an
@Stable
instance
B
. Does annotating the function with
@Stable
require that the instance
B
be returned every time
A
is passed in? Or could it return a different instance (
C
,
D
, ...) each time it is called with
A
, as long as the the returned value is "the same" (not necessarily
equal
or the same instance)?
it doesn't have to be the same instance, just make sure that calling
B.equals(C or D...)
will always return the same result whether it is
false
or
true
, this is what
@Stable
cares about , if
B
&
C
or
D
have the same values but for some reason or another their
equals
call isn't deterministc, then they shouldn't be marked as
@Stable
because compose compiler can recompose those incorrectly based on your assumption.
a

Andrew Hughes

08/23/2022, 8:48 PM
Oh, "the same result" is referring to the
equals
? It sounds like it's referring to the result of the function. If I'm understanding you correctly, that would mean any function that returns an
@Stable
value can be marked as
@Stable
. But I don't think that's the case. Maybe I'm misunderstanding.
m

MR3Y

08/23/2022, 8:49 PM
And what if
A
is mutated (while complying with the
@Stable
contract)? In my scenario, this could change the output of the function. The question is, how does that affect the stability of the function?
It is normal, The compose compiler would recompose that to read the updated value
the whole idea behind
@Stable
annotation is to aid the compiler in making smart optimizations for you for things that aren't optimized by default
But it does a good job optimizing many things for you under the hood, you should use @Stable if you are SURE that something isn't optimized by default & it should be optimized, otherwise you shouldn't care about anything because compiler is doing some optimizations under the hood, and if you annotated an API with Stable while it shouldn't be, the compiler would actually incorrectly recompose your code when it shouldn't be
If I'm understanding you correctly, that would mean any function that returns an
@Stable
value can be marked as
@Stable
. But I don't think that's the case. Maybe I'm misunderstanding.
You're right, any function that takes stable & returns stable can be marked as stable
a

Andrew Hughes

08/23/2022, 9:08 PM
👍 Yea, I'm not trying to put
@Stable
on a bunch of things. I just thought it might make sense for this once scenario, but I'm still not wrapping my head around it for functions. Here's what I'm doing: I've created a
TonalPalette
class that's basically a copy of the implementation of
ColorScheme
, but with all the base tonal values for each tonal range. This is annotated with
@Stable
, just like
ColorScheme
. Then I have a
fun TonalPalette.lightColorScheme(): ColorScheme
that creates a
ColorScheme
from the appropriate values from the
TonalPalette
(as well as a corresponding
TonalPalette.darkColorScheme()
function). Initially, it made sense to me that these functions could be annotated with
@Stable
as well, but now I'm not so sure. Does that make sense? The functions are used in our
AppTheme
composable, which wraps
MaterialTheme
, and determine the appropriate
ColorScheme
based on the current
TonalPalette
and
darkTheme
parameter. I assume it'd be helpful if the functions generating the
ColorScheme
only were called and/or created new
ColorScheme
whenever
TonalPalette
or
darkTheme
changes. Does that sound like an appropriate use of
@Stable
on these functions? Or should I just not worry about it?
You're right, any function that takes stable & returns stable can be marked as stable
Okay, then if a function takes a stable and returns a stable, does the compiler already implicitly mark it as stable? Or is it still necessary to manually annotate it?
m

MR3Y

08/23/2022, 11:06 PM
I've created a
TonalPalette
class that's basically a copy of the implementation of
ColorScheme
, but with all the base tonal values for each tonal range. This is annotated with
@Stable
, just like
ColorScheme
. Then I have a
fun TonalPalette.lightColorScheme(): ColorScheme
that creates a
ColorScheme
from the appropriate values from the
TonalPalette
(as well as a corresponding
TonalPalette.darkColorScheme()
function). Initially, it made sense to me that these functions could be annotated with
@Stable
as well, but now I'm not so sure. Does that make sense?
Yes, it perfectly makes sense
Okay, then if a function takes a stable and returns a stable, does the compiler already implicitly mark it as stable? Or is it still necessary to manually annotate it?
honestly, I'm not sure if the compiler would implicitly mark it or not, I would need to check the underlying code for that. But, I think the most common approach is to annotate that manually since there are many functions in compose UI, material, and foundation are already doing that
here are some examples of functions that are doing that: RowScope.weight ColumnScope.weight BoxScope.align
you can also refer to the declaration & the implementation of those functions if you still have some doubts about when to mark a function as a
@Stable
g

Grégory Lureau

08/24/2022, 8:01 AM
You're right, any function that takes stable & returns stable can be marked as stable
What if there is side effects (or even local random)? I think about a function using the system time or a static variable/function where the result can change depending of the timing of the call, and it impacts the output (let's say a stable data class that contain the result). If I get the goal of @Stable right, it should not be marked as stable because we want the compiler to call it again even if the parameters haven't changed. Am I right?
m

MR3Y

08/24/2022, 11:44 AM
generally, changing/reading global or static variables & changing the result based on that would be a bad practice because: • testing this function would be difficult • the behavior of the function wouldn't be easily known/deterministic for the caller of the function which might lead to obscure bugs That being said, the correct thing to do here IMO is to take that variable as a function parameter, and that would bring us back to ensuring that function parameters are stable to mark it as a
@Stable
. On a side note, I wanted to ask you one question, do you have a usecase for when a function that should be stable depends on some global variables? because I can't think of a usecase for it or haven't seen one like that yet. Or is it just a contrived example to better understand
@Stable
?
g

Grégory Lureau

08/24/2022, 11:56 AM
Contrived example tbh, and not pushing for this usage neither, but I can think of using Android applicationContext to get a resource for example. Given the access to context could be made static (applicationContext), or maybe coming directly from Compose via stuff like
LocalContext.current
because it's a @Composable method.
m

MR3Y

08/24/2022, 12:08 PM
probably you're taking about stateful modifiers here that are created with
composed
and allows you to access composable functions/getters inside
factory
lambda body. For example: Modifier.clickable is a stateful modifier. if you're talking about those, as far as I've seen, no, those aren't marked as
@Stable
most or all stateful modifiers from the official compose libraries aren't marked
@Stable