[英]Kotlin How can I call extension function
I want to call an extension function from MainActivity class in another class. 我想从另一个类的MainActivity类中调用扩展函数。 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
}
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). 将扩展属性设置为顶级(将其移至类之外)。
成员扩展仅在声明它们的类中可见。但是,您可以将扩展功能放在类之外,以便能够在其他任何地方导入和使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.