kotlin - 为什么我不能在 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")
}
}
谁能给我解释一下?:)
解决方案
您不能由此创建派生类。默认情况下,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()
}
推荐阅读
- ios - “未加载库 - 未找到合适的图像”错误
- google-cloud-bigtable - (BigTable Query, java API) 如何同时使用scan和rowKey?
- javascript - 带有弹出窗口和缩放到引脚的传单聚类标记在相同的纬度 lng 时关闭引脚
- angular - 如何使用 Ionic 4 从 ng-otp-input 获取和路由 otp 的编号?
- javascript - 当复选框为真时向元素添加文本
- javascript - Javascript - 素数函数问题,内存过载
- sql - 对 CASE WHEN 使用新变量
- python - 从 CSV 列中查找均值和方差
- powershell - 我的批处理脚本中的这行代码有什么问题?
- javascript - 视频标题自动播放问题