4

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?

Dmytro Rostopira
  • 10,588
  • 4
  • 64
  • 86
Rasoul Miri
  • 11,234
  • 1
  • 68
  • 78

3 Answers3

5

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

fun Log.Companion.i2(msg:String) {
 ...
}
Aseem Sharma
  • 1,673
  • 12
  • 19
  • I need to add function on android.util.Log class in android. not new custom class – Rasoul Miri Jul 10 '18 at 07:06
  • 2
    android.util.Log class is static, and to make extension function of a static class in Kotlin we need to use their companion object reference. Which if not possible in Log then I suggest to create `Any` extension function as per this [answer](https://stackoverflow.com/a/51259126/4878972) – Aseem Sharma Jul 10 '18 at 07:20
1

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

Milind Mevada
  • 3,145
  • 1
  • 14
  • 22
1

Currently, static extension methods in Kotlin is not supported without the companion object, because android.util.Log is a java class, so there is no companion object.

Instead, I recommend you to use a static function (package-level function, simply declared outside a class in a source code file):

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

And just use it like this:

logI2("activity_main")
Hong Duan
  • 4,234
  • 2
  • 27
  • 50