Kotlin – 延期上课
是否有可能创建类似String的final
类的扩展? 像在swift中一样,可以在final
class
的extension
中添加其他方法。
举个例子 – 我想创建一个String
扩展的方法,它会告诉我String
有有效的密码长度。
val password : String = mEdtPassword!!.getText().toString() // how to define haveValidLength method in extension val isValid : Boolean = password.haveValidLength()
注 – 这个例子只是为了理解extension
可用性,而不是真实的场景。
是的你可以。 Kotin 扩展方法提供了使用新功能扩展类的能力, 而不必从类继承或使用任何类型的设计模式(如装饰器)。
以下是String
的扩展方法:
// v--- the extension method receiver type fun String.at(value: Int) = this[value]
以下是Java生成的扩展方法代码:
public static char at(String receiver, int value){ return receiver.charAt(value); }
所以Kotlin的扩展方法是使用委托而不是继承。
然后你可以像下面这样调用一个扩展方法:
println("bar".at(1))//println 'a'
您还可以为现有的扩展功能编写扩展方法,例如:
fun String.substring(value: Int): String = TODO() // v--- throws exception rather than return "ar" "bar".substring(1)
但是您不能为现有的成员函数编写扩展方法,例如:
operator fun String.get(value: Int): Char = TODO() // v--- return 'a' rather than throws an Exception val second = "bar"[1]
试图添加更多的细节,这个答案可能对某人有帮助。
是的,我们可以将其他方法添加到像String
这样的final
类。 对于一个例子,我想在String
添加一个方法,它会告诉我,我的String
的密码是否有有效的字符数。
所以我要做的就是创建一个可以写在同一个class
或不同的单独的class
文件中的下面的函数。
fun String.hasValidPassword() : Boolean { // Even no need to send string from outside, use 'this' for reference of a String return !TextUtils.isEmpty(this) && this.length > 6 }
现在从任何地方打电话
val isValid : Boolean = password.haveValidLength()
建议
如果你的应用程序只有一个密码验证,那么没有问题。
但是,如果应用程序有多个验证,我不建议您编写这样的扩展方法hasValidPassword
。 由于扩展方法是饱和的 ,所以不能在运行时更改hasValidPassword
。 所以,如果你想在运行时改变验证,你应该使用一个函数,例如:
class PasswordRepository(private val validate:(String)->Boolean){ fun save(value:String){ if(validate(value)){ //TODO persist the password } } } val permitAll = PasswordRepository {true} val denyAll = PasswordRepository {false} permitAll.save("it will be persisted") denyAll.save("it will not be persisted")
换句话说,上面的扩展方法违反了单一责任原则 ,它进行验证和字符串操作。
你可以用Kotlin的扩展函数来做到这一点。 通过扩展,您可以为您有权访问的课程添加额外的功能; 例如遗留代码库。 在Kotlin文档中给出的例子中, swap
被添加到MutableList<Int>
没有swap
MutableList<Int>
中。 使用this
关键字是指交换功能将在其上运行的对象。 在下面的例子中, this
是指testList
val testList = mutableListOf(1, 2, 3) testList.swap(0, 2)
- Kotlin与地图(标记不显示)
- 在Kotlin中使用基于注释的依赖注入时,哪种语法是优选的?
- Kotlin原生等同于System.exit(-1)
- 我可以对来自Java API的平台类型执行无效安全吗?
- Kotlin javaClass <>在最新的Android Studio 3.0中缺少依赖关系
- 为什么我的代码无法访问?
- 我现在正在用Kotlin开发一个Android应用程序,但是发生了一个错误:CompilationException:无法将方法调用“readText”内联到
- Kotlin setTargetFragment
- RegisterResGeneratingTask已弃用,请使用registerGeneratedFolders(FileCollection)