Kaan
Kaan

Reputation: 73

Kotlin How can I call extension function

I want to call an extension function from MainActivity class in another class. How can i do this?

object MainActivity : AppCompatActivity() {

val StringBuilder.readHistory: StringBuilder
    get() {
        val temp = this@readHistory
        temp.setLength(0)
        try {
            val file = InputStreamReader(MainActivity.openFileInput(MainActivity.getString(R.string.dosyaadı)))
            val br = BufferedReader(file)
            var line = br.readLine()
            while (line != null) {
                temp.append(line + "\n")
                line = br.readLine()
            }
            br.close()
            file.close()
} catch (e: Exception) {
            e.printStackTrace()
        }
        return temp
    }

Upvotes: 1

Views: 2025

Answers (2)

zsmb13
zsmb13

Reputation: 89638

Member extensions are only visible within the class that they're declared in. However, you can place your extension function outside your class to be able to import and use it anywhere else.

Upvotes: 0

Salem
Salem

Reputation: 14967

You can't call this outside of the class, because it's nested inside this class and therefore only applies to that scope.

Make the extension property top-level (move it outside of the class).

Upvotes: 2

Related Questions