首页 > 解决方案 > 为什么我不能在 Kotlin 中用 Int() 继承函数类?

问题描述

下面的代码是一个继承主体内部函数的类。如果我使用 Any() 则该类是可继承的,但如果我使用 Int() 则该类不可继承。怎么能?

fun main (){
    number().me(23)
    number2().me(23)
}

class number : Int(){
    fun me(x : Int){
        println("I'm $x years old")
    }
}

class number2 : Any(){
    fun me(x : Int){
        println("I'm $x years old")
    }
}

谁能给我解释一下?:)

标签: kotlinkotlin-android-extensions

解决方案


您不能由此创建派生类。默认情况下,kotlin 将其作为“最终”类,最终类将无法拥有派生类(可继承)。

class AnyClassName 

但是你可以从这个类中派生出一个,只需在它前面添加'open'关键字

open class AnyClassName

kotlin 中的 int() 类是 final 类,所以它是可继承的。你可以打开它的声明,你会看到这个

public class Int private constructor() : Number(), Comparable<Int> {..}

另一边的 Any() 是 'open' 类,因为它前面有关键字 open。您可以从中创建派生类。Any() 也是 kotlin 中所有类的根。

如果你想向 Int() 类添加功能,你可以创建一个扩展函数,而不是从它派生(因为你当然不能)。所以在你的情况下

fun Int.number() : Unit {
    println("I'm $this years old")
}

在你的主要功能中

fun main (){
    23.number()
}

推荐阅读