Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add extension on Log in android (Kotlin)

I use this code to add extension for Log class android

fun Log.i2(msg:String):Unit{
    Log.i("Test",msg)
}

when using in the activity

class MainActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.i2("activity_main")
    }
}

Log.i2 not found. What's wrong?

like image 453
Rasoul Miri Avatar asked Mar 05 '23 20:03

Rasoul Miri


2 Answers

To achieve extension function in static class, you need to write extension of the companion object(refer this)

fun Log.Companion.i2(msg:String) {
 ...
}
like image 97
Aseem Sharma Avatar answered Mar 15 '23 19:03

Aseem Sharma


You have created Extension function of Class Log. Which is suppose to call by Instance of Class Log. You are trying to treat extension function as static and calling it by Class name. Which is not correct in the case

like image 24
Milind Mevada Avatar answered Mar 15 '23 18:03

Milind Mevada