Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - How i can access my new class extension function from another file

I am very new to Kotlin.

I want to be able to add a function to my abstract class, so when I define that function I will be able to invoke that on every child from that class(they inherit the abstract class)

However,I want to define those extension functions in other file. I can't access those functions when i try to invoke them on a particular child implementation of the abstract class.

What are the rules, that I need to made to resolve my problem?

I want to by able achieve something like this:

abstract class Parent(val val1, val val2, val val3){}

class Child(var val1, var val2, var val3) : Parent(val1, val2, val3){}

class Child2(var val1, var val2, var val3) : Parent(val1, val2, val3){}

The extension method for parent and all childs:

 fun Parent.convertToChild2( ): Child2? {

return //some creation method of Child2
} 

And I want to be able to invoke this:

child: Child
child.convertToChild2

I defined all classes in separate file and also the extension function in other file.

I cannot access the function like this - is not visible.

like image 630
K.Os Avatar asked Oct 02 '17 10:10

K.Os


People also ask

How do I call Kotlin extension function?

Kotlin extension function example For doing this we create an extension function for MutableList<> with swap() function. The list object call the extension function (MutableList<Int>. swap(index1: Int, index2: Int):MutableList<Int>) using list. swap(0,2) function call.

How do I extend one class to another in Kotlin?

In Kotlin we use a single colon character ( : ) instead of the Java extends keyword to extend a class or implement an interface. We can then create an object of type Programmer and call methods on it—either in its own class or the superclass (base class).

When would you use Kotlin extension function?

In particular, Kotlin extensions let you add functions to a class that you cannot modify. By using them, you will be able to call these new functions as if they were part of the original class. Similarly, you can use this mechanism to add new properties to existing classes. You can also extend Kotlin companion objects.


1 Answers

The answer for my question, that satisfies me is just to extract the method to some "object" structure in other file and whenever we want to access that function we must import the path(package.object.method) to this.

But the problem is, that IDE is not propose me the path to my extension function - i must import it by myself.

I am using Android Studio 3 preview, hope this will be fixed.

UPDATE

It is better to define those function in just plain Kotlin file, so the functions will be not owned by any structure. Then it will be not a problem with importing those automatically by IDE from any place.

like image 140
K.Os Avatar answered Oct 06 '22 10:10

K.Os