Kotlin Parameter specified as non-null is null
版權聲明:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/chf1142152101/article/details/78275298
報錯信息如下:
java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter animation at cn.enjoytoday.expandmateriallayout.ExpandRefreshLayout$mRefreshListener$1.onAnimationEnd(ExpandRefreshLayout.kt:0) at cn.enjoytoday.expandmateriallayout.ExpandRefreshLayout$HeadViewContainer.onAnimationEnd(ExpandRefreshLayout.kt:1099) at android.view.ViewGroup.finishAnimatingView(ViewGroup.java:6293) at android.view.View.draw(View.java:17180) ......
kotlin 中對於回調對象若是為說明可以為空的情況下,kotlin 會自動對齊對象進行非空檢查,就會報出如上錯誤,檢查代碼發現是設置接口的參數和創建的接口的回調參數的類型設置不一致,如下:
//創建的接口: private animationListener = object: Animation.AnimationListener { override fun onAnimationStart(animation:Animation) { ...... } override fun onAnimationRepeat(animation:Animation) {} override fun onAnimationEnd(animation:Animation) { log(message = "onAnimationEnd") ...... } } //監聽的類的聲明 class CustomLayout(context:Context):LinearLayout(context){ private var listener: Animation.AnimationListener? = null fun setAnimationListener(listener: Animation.AnimationListener?) { this.listener = listener } public override fun onAnimationStart() { super.onAnimationStart() log(message = "onAnimationStart animation is null :${animation==null}") listener?.onAnimationStart(this.animation) } public override fun onAnimationEnd() { super.onAnimationEnd() log(message = "onAnimationEnd animation is null :${animation==null}") listener?.onAnimationEnd(this.animation) } } //使用 fun useMethod(){ val layout=CustomLayout(context) val animation=ScaleAnimation(1f, 0f, 1f, 1f, Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_PARENT, 0.5f); layout.setAnimationListener(animationListener) layout.clearAnimation() layout.startAnimation(animation) }
如上代碼所示,通過運行 useMethod 方法,出現 “Parameter specified as non-null is null”報錯,解決方法很簡單,將我們設置的接口回調參數設置為可空類型即可,如下:
//創建的接口,目前就log看可知,onAnimationStart時animation為非空,onAnimationEnd為空 //因此,也可單獨只對onAnimationEnd(animation:Animation)修改. private animationListener = object: Animation.AnimationListener { override fun onAnimationStart(animation:Animation?) { ...... } override fun onAnimationRepeat(animation:Animation?) {} override fun onAnimationEnd(animation:Animation?) { log(message = "onAnimationEnd") ...... } }