我可以将类作为扩展添加到Kotlin中的另一个类吗?

时间:2019-05-23 06:58:15

标签: class kotlin

例如,我知道我可以像这样向String类添加扩展名:

gender_value<-function(author){
 au<-sub("([^,]+),\\s*(.*)", "\\2 \\1", author)
 r<-GET(paste0("https://genderapi.io/api?name=",au))
 g<-content(r)$gender
 n<-c(au,g)}

author("nandan,vivek","paswan, jyoti")

现在我想将类作为扩展名添加到另一个类中,我认为实现将是这样的:

val String.isValidEmail : Boolean
    get() {
        val expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"
        val pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        val matcher = pattern.matcher(this)
        return matcher.matches()
    }

但是,这给了我“ Networking.Email”的错误。对于“网络”部分:重新声明:网络。对于“电子邮件”部分:期待顶级声明。在科特林真的有可能吗?

1 个答案:

答案 0 :(得分:0)

不,Kotlin中没有扩展类之类的东西。参见here

  

Kotlin与C#和Gosu类似,提供了扩展类的能力   具有新功能,而不必从类继承或使用   任何类型的设计模式,例如Decorator。这是通过特殊方式完成的   声明称为扩展。 Kotlin支持扩展功能   和扩展属性。