Use worldwide extension method / property

In Kotlin, you can define extension methods and properties for existing classes:

operator inline fun Vector2.plus(other: Vector2) = Vector2(x + other.x, y + other.y)

This allows you to do this:

val result = Vector2(1.1f, 2.3f) + Vector2(2f, 4f)

Is there a way to make this extension global, so I don’t need to import it into every class that uses this?

+4
source share
1 answer

You cannot do this because extension methods are statically replicated by the compiler.

Without import, the compiler does not know about the extension.

+7
source

Source: https://habr.com/ru/post/1648025/


All Articles