Home > Blockchain >  What if use apply class property instead of newInstance()?
What if use apply class property instead of newInstance()?

Time:03-16

We use this factory method pattern for re-instatiate fragment to protect data in constructor.. and then,, I thought... what if I use empty constructor and apply property??

What is difference between these two method?

  1. normal method
class A(){
    private val str = ""

    override onCreate(~~~){
         str = argument.getString("key")
    }

    companion object{
      fun newInstance(){
        return A().apply {
            arguments = Bundle().apply {
                putString("key", str)
            }
        }
      }
    }
}
  1. method I am wondering
class A(){
    val str = ""
}

other class{
    A().apply{
        str = "I am A"
    }
}

CodePudding user response:

Using apply doesn't solve anything. Is just a shortcut for "fixing" the instance of a class you're working with.

It's exactly the same as if you were to do:

val a = A()
a.str = "I am A"

No difference.


The thing about Fragments is that you must be using arguments to pass data to them. This is because Fragments can be re-created by the FragmentManager and field values (str field in your example) will be lost, but arguments Bundle will be retained.

You can do that however you want. Factory functions - newInstance - are just a well known simple pattern that tries to force using arguments.

  • Related