Kotlin-延期上课 [英] Kotlin - Extension for final class
问题描述
是否可以创建final
类的扩展,例如String?像在 swift 中一样,可以在final
class
的extension
内添加其他方法.
Is it possible to create extension of final
classes like String? Like in swift it is possible to add additional methods inside a extension
of final
class
.
例如-我想在String
扩展名中创建一个方法,该方法将告诉我String
具有有效的密码长度.
For an example - I would like to create a method in String
extension which will tell me String
have valid length for password.
val password : String = mEdtPassword!!.getText().toString()
// how to define haveValidLength method in extension
val isValid : Boolean = password.haveValidLength()
注意-该示例仅是为了了解extension
的可用性,而不是实际情况.
Note - That example is just for a sake to understand usability of extension
, not a real scenario.
推荐答案
是的,可以. Kotin 扩展方法提供了使用新功能扩展类的能力从类继承或使用任何类型的设计模式(例如Decorator).
yes, you can. Kotin extension method provides the ability to extend a class with new functionality without having to inherit from the class or use any type of design pattern such as Decorator.
以下是String
的扩展方法:
// v--- the extension method receiver type
fun String.at(value: Int) = this[value]
以及以下以Java生成的扩展方法代码:
And the extension method code generated as Java below:
public static char at(String receiver, int value){
return receiver.charAt(value);
}
因此Kotlin中的扩展方法是使用委托而不是继承.
So an extension method in Kotlin is using delegation rather than inheritance.
然后,您可以像下面这样调用扩展方法作为其成员函数:
Then you can calling an extension method like as its member function as below:
println("bar".at(1))//println 'a'
您还可以为现有扩展功能编写扩展方法,例如:
You also can write an extension method for the existing extension function, for example:
fun String.substring(value: Int): String = TODO()
// v--- throws exception rather than return "ar"
"bar".substring(1)
但是您不能为现有成员函数编写扩展方法,例如:
But you can't write an extension method for the existing member function, for example:
operator fun String.get(value: Int): Char = TODO()
// v--- return 'a' rather than throws an Exception
val second = "bar"[1]
这篇关于Kotlin-延期上课的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!