I have a language/syntax question, I stumbled on ...
# android
t
I have a language/syntax question, I stumbled on it in Android... I was looking at some code that read:
supportFragmentManager.commit {
...
}
When I see this pattern, I think "trailing closure syntax". On closer examination, I realized that
this
in said closure-esque body wasn't what I thought it was, so I went and found the method signature for FragmentManager.commit...
FragmentManager.commit(allowStateLoss: Boolean = false, body: FragmentTransaction.() -> Unit
I know that () -> Unit is a nullary closure, but what does it mean when I see the above? ClassName.() -> Unit?
t
Thank you so much @Zach Klippenstein (he/him) [MOD]! I totally get how these work now. I don't like them at all, but it makes sense how it works. A similar feature in Swift to enable SwiftUI (a "DSL") has been controversial. But I'll make due with it. Can one still name an explicit parameter with one of these? I'll have to experiment with it to see. I would prefer the explicit parameter, because I prefer explicit scope. Scope resolution that wanders as your eyes pan over code leads to spaghetti imo.
z
Yep, they’re definitely something you have to be careful with and use judiciously. There’s no way to name them, but IntelliJ has an auto fix to convert a receiver to a parameter and back.