Sahil Shokeen
Sahil Shokeen

Reputation: 336

Android FragmentManager extension function working

I saw in Google IO code this extension function for FragmentManager.

/**
* Allows calls like
*
* `supportFragmentManager.inTransaction { add(...) }`
*/
inline fun FragmentManager.inTransaction(func: FragmentTransaction.() ->FragmentTransaction) 
{
    beginTransaction().func().commit()
}

It is used like this:

supportFragmentManager.inTransaction {
            add(R.id.fragment_container, OnboardingFragment())
        }

Can someone explain what type is this func variable in inTransaction method?

I know this is of type lambda but what is the argument of that lambda here "Fragmenttransaction.()"?

Upvotes: 0

Views: 239

Answers (1)

Rajan Kali
Rajan Kali

Reputation: 12953

I'll try to explain each statement meaning in func: FragmentTransaction.() -> FragmentTransaction

func is nothing but a variable name, it can be anything not necessarily func.

FragmentTransaction.() is the type of variable passed into method, meaning it is a extension of FragmentTransaction, with .() , the lambda is in scope of FragmentTransaction meaning inside lamba you will have access to FragmentTransaction using this, that is why you can directly access add, replace and other transaction methods inside lambda scope.

-> FragmentTransaction means this method/lambda will return value of type FragmentTransaction which will be used by caller to get the FramgmentTransaction

inline fun FragmentManager.inTransaction is an extension function on FragmentManager, by calling beginTransaction it now has FragmentTransaction and calling func will apply necessary transformations to transaction and will return it which then used to commit the transaction.

UPDATE

when you call beginTransaction() it will return a FragmentTransaction, on which func can be called as extension function,

inline fun FragmentManager.inTransaction(func: FragmentTransaction.() ->FragmentTransaction) 
{
    val transaction: FragmentTransaction = beginTransaction()
    transaction.func().commit()
}

Take a look at below example for different ways of appending strings to StringBuilder

 //traditional way
 fun toString(stringBuilder: StringBuilder): String{
     return stringBuilder.toString()
 }
    
 fun StringBuilder.append1(): StringBuilder{
     append(1)
     return this
 }

 fun StringBuilder.append2(): StringBuilder{
     append(2)
     return this
 }
    
 //extenison as parameter
 fun toString(builder: StringBuilder.() -> StringBuilder): String{
    return builder().toString()
 }
    
 fun test(){
     //here based on your need , multiple extension functions are created
     val stringBuilder = StringBuilder()
     val s1 = toString(stringBuilder.append1())
     val s2 = toString(stringBuilder.append2())
     
     //modifying string builder extension dynamically
     val t1 = toString { append(1) }
     val t2 = toString { append(2) }
 }

Upvotes: 1

Related Questions