https://kotlinlang.org logo
Title
v

vbsteven

03/15/2023, 7:38 PM
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
val application = Application("myapp", ApplicationFlags.NONE.or(ApplicationFlags.REPLACE))
where I want the signature to read something like
class Application(val name: String, flags: ApplicationFlags)
So the user does not have to go hunt for random constants.
k

kevin.cianfarini

03/15/2023, 7:44 PM
v

vbsteven

03/15/2023, 7:51 PM
Thanks, that
OptionSet
you proposed in the thread looks interesting.
k

kevin.cianfarini

03/15/2023, 8:06 PM
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

vbsteven

03/15/2023, 8:09 PM
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

kevin.cianfarini

03/15/2023, 8:11 PM
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.
@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

vbsteven

03/15/2023, 8:12 PM
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

kevin.cianfarini

03/15/2023, 8:13 PM
No problem