Reputation: 62519
I have created a fragment using Kotlin and you know how there is a convenience static method to set the fragment args in Java. Like this:
public static MyFragment newInstance(Bundle args){
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}
I'm trying to accomplish this in Kotlin using a companion object since it's static. Here is what I have so far which compiles:
companion object {
fun newInstance(@Nullable b: Bundle): MyFragment {
val frag = MyFragment()
frag.arguments = b
return frag
}
}
I was thinking that if I use the @Nullable
annotation that I would be allowed to pass in null for the bundle but I keep getting the following error when I call MyFragment.newInstance(null)
:
FATAL EXCEPTION: main Process: com.mobile.MyApp.labs, PID: 5758 java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter b at com.mobile.MyApp.ui.cart.fragments.MyFragment$Companion.newInstance(MyFragment.kt:0) at com.mobile.MyApp.ui.cart.fragments.CartDetailsFragment.onCtaClicked(CartDetailsFragment.java:521) at com.mobile.MyApp.ui.cart.fragments.CartDetailsFragment_ViewBinding$1.doClick(CartDetailsFragment_ViewBinding.java:66) at butterknife.internal.DebouncingOnClickListener.onClick(DebouncingOnClickListener.java:22) at android.view.View.performClick(View.java:6256) at android.view.View$PerformClick.run(View.java:24701) at android.os.Handler.handleCallback(Handler.java:789) at android.os.Handler.dispatchMessage(Handler.java:98) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
How can I pass in null
?
Upvotes: 0
Views: 2412
Reputation: 3976
Kotlin provide (?) FOR handling null
.have look
companion object {
fun newInstance( b: Bundle?): MyFragment {
val frag = MyFragment()
frag.arguments = b
return frag
}
}
Hope it will help you.
Upvotes: 0
Reputation: 8371
In Kotlin, you don't pass @Nullable
but rather write a question mark (?
) behind the type name to mark it nullable.
fun newInstance(b: Bundle?): MyFragment
Upvotes: 6