Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add lambdas to property delegation for default values #173

Open
jbruchanov opened this issue Nov 13, 2023 · 1 comment
Open

Add lambdas to property delegation for default values #173

jbruchanov opened this issue Nov 13, 2023 · 1 comment

Comments

@jbruchanov
Copy link

jbruchanov commented Nov 13, 2023

currently, there is defaultValue argument as simple value like this...

var someValue: Int by settings.int("key", defaultValue = -1)

I'd be nice to have the default value deferred to the time when it's actually read, so I can use for example remote config or any other external dependency which might have some async loading with some default fallback like android/firebase remote config has.

usage would be for example this, so the remote config value would be used at the time when the someValue is actually read and not at the time when the owner instance object is created, then it gives a time potentially to remote config to sync

var someValue: Int by settings.int("key", { remoteConfig.key() } )
@russhwolf
Copy link
Owner

russhwolf commented Nov 14, 2023

I'm wary of adding more variants to the existing API since there's already a lot of different calling conventions between nullable and non-null standard getters, operator getters, delegates, suspend/flow stuff, etc. I'll think about this, though. It might work well as a separate module. In the meantime, you can implement it yourself by doing something like

fun Settings.getInt(key: String, defaultValue: () -> Int): Int = 
    if (hasKey(key)) getInt(key, 0) else defaultValue()

For delegates you can copy the machinery of the existing delegate APIs and create analogues that call into that new function.

If you try handrollling it like that, let me know how it works for you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants