简体   繁体   中英

Kotlin inner interface declaration in class

I'm newby in Kotlin and need to re-write the following Java class to Kotlin, and can't figure it out how to implement it.

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


        private Listener listener;



   .....
}

So that to use "listener" in @Ovveride onAttach(..) methods as

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

----------------- UPDATE --------------------

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)
        }
    }

If you're using Android Studio, and you copy-paste this code into your IDE, it will automatically ask you if you want it to convert it into Kotlin on its own.

Try that out.

Nevertheless, if you're trying to create a one-function interface in Kotlin I would recommend you use a High-Order function instead.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM