3

是否可以创建final像 String 这样的类的扩展?就像在swiftextension中一样,可以在 a of中添加其他方法final class

举个例子 - 我想在String扩展中创建一个方法,它会告诉我String密码的有效长度。

 val password : String = mEdtPassword!!.getText().toString()

 // how to define haveValidLength method in extension
 val isValid : Boolean = password.haveValidLength()

注意 - 该示例只是为了了解 的可用性extension,而不是真实场景。

4

3 回答 3

4

是的你可以。Kotin扩展方法提供了使用新功能扩展类的能力,而无需从类继承或使用任何类型的设计模式,例如装饰器。

下面是 a 的扩展方法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]
于 2017-07-22T12:59:10.353 回答
1

尝试添加更多详细信息,此答案可能对某人有所帮助。

是的,我们可以向final诸如String. 例如,我想添加一种方法,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但是,如果应用程序有多个验证,我不建议您编写这样的扩展方法。由于扩展方法是satically,因此您无法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")

换句话说,上面的扩展方法违反了单一职责原则,它进行了验证和字符串操作。

于 2017-07-22T13:31:32.800 回答
0

您可以使用 Kotlin 中的扩展函数来做到这一点。通过扩展,您可以为您可以访问或无法访问的类添加额外的功能;例如遗留代码库。在此处的 Kotlin 文档中给出的示例中,swap添加了最初MutableList<Int>没有的内容swap。使用的this关键字是指交换功能将对其进行操作的对象。在下面的例子中,thistestList

val testList = mutableListOf(1, 2, 3)
testList.swap(0, 2)
于 2017-07-22T13:14:29.247 回答