Access variable initialized in a lambda passed to function


For example i made this function:

fun Context.prefs(f: SharedPreferences.() -> Unit){
val preferences = getSharedPreferences(“prefs”, Context.MODE_PRIVATE)

Now how to use it in code:

prefs {
var s = getString(“value”, “default value”)

//what if i need “s” outside this lambda? i have to put all the code inside prefs {}. Is there a way, besides making the variable “s” a nullable field in class?


I’d do:

var s = ""
prefs {
s = getString(“value”, “default value”)

with s as a local variable