简体   繁体   中英

Kotlin Anonymous Inner Class

I have the following code snippets Please help me figure out the difference between the same

Snippet 1

    navbar.setOnItemSelectedListener { id ->
        var fragment: Fragment? = null
        when (id) {
            R.id.home -> fragment = HomeFragment()
            R.id.graphical_stats -> fragment = GraphicalStats()
            R.id.sources -> fragment = SourcesFragment()
        }
        if (fragment != null) {
            supportFragmentManager.beginTransaction().replace(R.id.container_frame, fragment)
                .commit()
        } else {
            Log.e(TAG, "Error Creating Fragment")
        }
    }

Snippet 2

navbar.setOnItemSelectedListener { object : ChipNavigationBar.OnItemSelectedListener{
        override fun onItemSelected(id: Int) {
            var fragment: Fragment? = null
            when (id) {
                R.id.home -> fragment = HomeFragment()
                R.id.graphical_stats -> fragment = GraphicalStats()
                R.id.sources -> fragment = SourcesFragment()
            }
            if (fragment != null) {
                supportFragmentManager.beginTransaction().replace(R.id.container_frame, fragment)
                    .commit()
            } else {
                Log.e(TAG, "Error Creating Fragment")
            }
        }

I am using ChipNavigationBar and have three fragments namely Home Graphical Stats and Sources which will be created or swapped accordingly

Functionality wise, both the snippets are the same.

Snippet 1 is using a lambda expression for setOnItemSelectedListener whereas the Snippet 2 uses a singleton object implementing the interface ChipNavigationBar.OnItemSelectedListener.

To simply your code, you should use a lambda expression. Also, you can use lambda expression only if your interface has only 1 function that's need to overridden.

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