Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么可以';我在Kotlin中用Int()继承函数类吗?_Kotlin_Kotlin Android Extensions - Fatal编程技术网

为什么可以';我在Kotlin中用Int()继承函数类吗?

为什么可以';我在Kotlin中用Int()继承函数类吗?,kotlin,kotlin-android-extensions,Kotlin,Kotlin Android Extensions,下面的代码是一个类,它继承了主体内部的函数。如果使用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(){ f

下面的代码是一个类,它继承了主体内部的函数。如果使用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中的所有类都有一个公共超类
Any
,即 未声明超类型的类的默认超类:

class Example // Implicitly inherits from Any
Any有三种方法:
equals()
hashCode()
toString()
。因此,他们 为所有Kotlin类定义

默认情况下,Kotlin类是最终类:它们不能被继承。使 一个可继承的类,用
open
关键字标记它

open class Base //Class is open for inheritance

,因此您无法对其进行扩展。

您无法由此生成派生类。默认情况下,kotlin将其设置为“final”类,final类将不能具有派生类(可继承)

但是你可以从这个类派生,只需在它前面加上“open”关键字

open class AnyClassName
kotlin中的Int()类是最后一个类,因此它是可继承的。你可以打开它的声明,你会看到这个

public class Int private constructor() : Number(), Comparable<Int> {..}
在你的主要功能中

fun main (){
    23.number()
}

我认为错误消息的解释已经足够了:
无法访问“”:它在“Int”中是私有的。此类型是最终类型,因此它不能从
继承。你有没有换一个?
fun Int.number() : Unit {
    println("I'm $this years old")
}
fun main (){
    23.number()
}