Rah*_*hul 5 kotlin kotlin-extension
是否可以创建final像 String 这样的类的扩展?就像在swift中一样,可以在extensionof中添加其他方法final class。
举个例子 - 我想在String扩展中创建一个方法,它会告诉我String密码的有效长度。
val password : String = mEdtPassword!!.getText().toString()
// how to define haveValidLength method in extension
val isValid : Boolean = password.haveValidLength()
Run Code Online (Sandbox Code Playgroud)
注意 - 该示例只是为了了解 的可用性extension,而不是真实场景。
是的你可以。Kotin扩展方法提供了用新功能扩展类的能力,而无需从类继承或使用任何类型的设计模式(例如 Decorator)。
下面是 a 的扩展方法String:
// v--- the extension method receiver type
fun String.at(value: Int) = this[value]
Run Code Online (Sandbox Code Playgroud)
Java 生成的扩展方法代码如下:
public static char at(String receiver, int value){
return receiver.charAt(value);
}
Run Code Online (Sandbox Code Playgroud)
因此,Kotlin 中的扩展方法是使用委托而不是继承。
然后您可以调用扩展方法,如下所示:
println("bar".at(1))//println 'a'
Run Code Online (Sandbox Code Playgroud)
您还可以为现有的扩展函数编写扩展方法,例如:
fun String.substring(value: Int): String = TODO()
// v--- throws exception rather than return "ar"
"bar".substring(1)
Run Code Online (Sandbox Code Playgroud)
但你不能为现有的成员函数编写扩展方法,例如:
operator fun String.get(value: Int): Char = TODO()
// v--- return 'a' rather than throws an Exception
val second = "bar"[1]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5806 次 |
| 最近记录: |