SuperStar
SuperStar

Reputation: 41

Use a method of a class in another class

I have 2 kotlin files, each contains a class, first.kt contains class First and second.kt contains class Second.

In First, I have a method named "Create".

I wanna use the Create method in Second, but I don't want to create an instance of First.

I'm new in kotlin, I want something like static methods in c#

Upvotes: 1

Views: 518

Answers (1)

mehul bisht
mehul bisht

Reputation: 742

You can use companion object for that. Then import the method from First like this

First.kt

class First {

    companion object {
        fun create() {

            println("Hello from create")
        }
    }
}

Second.kt

import First.Companion.create

class Second {

    fun getData() {
        create()
    }
}

Upvotes: 5

Related Questions