https://kotlinlang.org logo
#compose-android
Title
# compose-android
a

Alexander Bliznyuk

10/16/2023, 9:24 AM
Hello, I have some question about stability/immutability for classes. Here is some example:
Copy code
data class MyString(
	private val stringResId: Int,
	private val args: List<MyString>,
) {
	
	@Composable
	fun getText(): String {
		val mappedArgs: Array<String> = args.map { it.getString() }.toTypedArray()
        return stringResource(textResId, *mappedArgs)
	}
}
As I understand, I can mark getText function as
@ReadOnlyComposable
, but what about the whole class ? Can I mark it as
Immutable
or
Stable
, or none of these annotations can be applied to this class? And one more example:
Copy code
data class MyColor(
    private val colorGetter: (@Composable () -> Color)
) {

    @Composable
    fun getColor(): Color {
        return colorGetter()
    }
}
Usage
Copy code
val color = MyColor {
    MaterialTheme.colorScheme.primary
}
z

Zach Klippenstein (he/him) [MOD]

10/16/2023, 4:32 PM
You can mark your class stable if you guarantee the List implementation will be stable (eg SnapshotStateList), and immutable if you guarantee the List impl will be immutable
a

Alexander Bliznyuk

10/16/2023, 7:05 PM
thanks for the answer. I also thought about this, but my concerns were
getColor()
can return different values in case if MaterialTheme is changed from light to dark, for instance
z

Zach Klippenstein (he/him) [MOD]

10/16/2023, 7:28 PM
That’s fine, the function itself isn’t changing
5 Views