Simplify assigning properties with Apply in Kotlin

January 15, 2019

Kotlin has this nice apply function that is an extension that allows you to set multiple properties at one time. It returns itself after being called.

// Normal approach
fun createInstance(args: Bundle) : MyFragment {
    val fragment = MyFragment()
    fragment.arguments = args
    return fragment
}
// Improved approach
fun createInstance(args: Bundle) 
              = MyFragment().apply { arguments = args }