The best practice on Android for creating a Fragment is to use a static factory method and pass arguments in a Bundle via setArguments().
In Java, this is done something like:
public class MyFragment extends Fragment {
static MyFragment newInstance(int foo) {
Bundle args = new Bundle();
args.putInt("foo", foo);
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}
}
In Kotlin this converts to:
class MyFragment : Fragment() {
companion object {
fun newInstance(foo: Int): MyFragment {
val args = Bundle()
args.putInt("foo", foo)
val fragment = MyFragment()
fragment.arguments = args
return fragment
}
}
}
This makes sense to support interop with Java so it can still be called via MyFragment.newInstance(...), but is there a more idiomatic way to do this in Kotlin if we don't need to worry about Java interop?