Any ideas on a good approach to map C bitfields of...
# kotlin-native
v
Any ideas on a good approach to map C bitfields often used as flags in C functions to a nice typesafe (or at least descriptive/discoverable) Kotlin API ? I'm trying to become an API like
Copy code
val application = Application("myapp", ApplicationFlags.NONE.or(ApplicationFlags.REPLACE))
where I want the signature to read something like
Copy code
class Application(val name: String, flags: ApplicationFlags)
So the user does not have to go hunt for random constants.
k
v
Thanks, that
OptionSet
you proposed in the thread looks interesting.
k
If you want to do this in an allocation free way I suggest not using the
OptionSet
interface and instead just exposing utility functions atop a
value class
.
v
I'm still looking into it and experimenting, for the thing I'm working on they are mostly used for infrequent UI-thread method calls, so having the allocation does not hurt performance that much I guess.
I'm not very familiar with value classes in Kotlin, so that's another thing I'll have to look into
k
The tl;dr on value classes is that if you don’t use them in a way that requires polymorphism (eg referring to it as an interface type), then whatever the value class wraps is what’s passed around in bytecode. There’s no allocations, no pointer chasing, etc.
If you’re familiar with Compose,
Dp
is a value class.
Copy code
@Immutable
@kotlin.jvm.JvmInline
value class Dp(val value: Float) : Comparable<Dp> {
At runtime only a float will get passed around, not an instance of
Dp
(unless it’s referred to as a
Comparable<Dp>
)
v
I've seen it but not used it that much, my general dislike for Compose/SwiftUI/React is the reason I'm looking in KN/GTK...
but that's very useful information on the value classes. thanks
k
No problem