class 中的 Kotlin 内部接口声明

Kotlin inner interface declaration in class

我是 Kotlin 的新手,需要将以下 Java class 重写为 Kotlin,但不知道如何实现它。

public class TestFragment extends ListFragment {
        
        static interface Listener {
            void itemClicked(long id);
        };


        private Listener listener;



   .....
}

以便在@Ovveride onAttach(..) 方法中使用“侦听器”作为

override fun onAttach(Context context) {
super.onAttach(context)
listener = context as Listener
}

----------------更新---------------- ---

class TestFragment: ListFragment() {

    internal interface Listener {
        fun itemClicked(id: Long)
    }

    private var listener: Listener? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        listener = context as Listener
    }

    override fun onListItemClick(listView: ListView, itemView: View, position: Int, id: Long) {
        if (listener != null) {
            listener!!.itemClicked(id)
        }
    }

如果您使用的是 Android Studio,并且您将这段代码复制并粘贴到您的 IDE 中,它会自动询问您是否希望它自行将其转换为 Kotlin。

试试看。

不过,如果您尝试在 Kotlin 中创建单功能界面,我建议您改用 High-Order function