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.andro id.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
How can I pass in null
?
在Kotlin中,您不会传递@Nullable
而是在类型名称后面写一个问号( ?
)以将其标记为可为空。
fun newInstance(b: Bundle?): MyFragment
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.