kotlin中使用Java接口,报错Parameter specified as non-null is null

Posted 怪兽N

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了kotlin中使用Java接口,报错Parameter specified as non-null is null相关的知识,希望对你有一定的参考价值。

文章目录

简述

kotlin中使用Java接口,报错Parameter specified as non-null is null

问题

2021-07-06 09:33:35.053 2317-2317/com.lqbs.piot E/androidRuntime: FATAL EXCEPTION: main
    Process: com.lqbs.piot, PID: 2317
    java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter hittingNode

原因分析

有一个接口TreeViewControlListener.class

public interface TreeViewControlListener 
    int MIN_SCALE  = -1;
    int FREE_SCALE = 0;
    int MAX_SCALE  = 1;
    void onScaling(int state, int percent);
    void onDragMoveNodesHit(NodeModel<?> draggingNode,NodeModel<?> hittingNode,View draggingView,View hittingView);

对应实现

binding!!.baseTreeView.setTreeViewControlListener(object : TreeViewControlListener 
            override fun onScaling(state: Int, percent: Int) 
				...
            

            override fun onDragMoveNodesHit(
                draggingNode: NodeModel<*>,
                hittingNode: NodeModel<*>,
                draggingView: View,
                hittingView: View
            ) 
               ...
            
        )

当在java中调用’onDragMoveNodesHit’方法传入null参数时,会crash。如下

if(listener!=null)
    listener.onDragMoveNodesHit(draggingNode,null,draggingView,null);

解决方案

首先,在java接口中添加@Nullable注解,这样在自动生成Kotlin实现接口代码时,就会可空,所以改为如下

TreeViewControlListener.class

public interface TreeViewControlListener 
    int MIN_SCALE  = -1;
    int FREE_SCALE = 0;
    int MAX_SCALE  = 1;
    void onScaling(int state, int percent);
    void onDragMoveNodesHit(@Nullable NodeModel<?> draggingNode, @Nullable NodeModel<?> hittingNode, @Nullable View draggingView, @Nullable View hittingView);

根据实际情况,实现接口代码,添加?表示可空

override fun onDragMoveNodesHit(
    draggingNode: NodeModel<*>?,
    hittingNode: NodeModel<*>?,
    draggingView: View?,
    hittingView: View?
) 
    ....

以上是关于kotlin中使用Java接口,报错Parameter specified as non-null is null的主要内容,如果未能解决你的问题,请参考以下文章

kotlin中使用Java接口,报错Parameter specified as non-null is null

kotlin中使用Java接口,报错Parameter specified as non-null is null

kotlin使用代码javaClass或class.java报错:unresolved reference

错误记录记录 Android 命令行执行 Java 程序中出现的错误 ( dx 打包 PC 可执行文件报错 | dalvik 命令执行 kotlin 编译的 dex 文件报错 )

Kotlin的报错提示:java.lang.NumberFormatException: For input string: ““

Kotlin的报错提示:java.lang.NumberFormatException: For input string: ““