Inheritance 科特林:“这是我的工作。”;val someVar=if(xx)1 else 1.0“;,为什么someVar是一个;有什么;?

Inheritance 科特林:“这是我的工作。”;val someVar=if(xx)1 else 1.0“;,为什么someVar是一个;有什么;?,inheritance,types,casting,kotlin,Inheritance,Types,Casting,Kotlin,首先,我尝试: interface Super class A : Super class B : Super val a = if (System.currentTimeMillis() >= 100) A() else B() 我按了Ctrl Q来检查a的类型。正如预期的那样,它是超级的 但当我尝试时: val someVar = if (System.currentTimeMillis() > 0) 1 else 1.0 它说someVar是Any。问题是:Double和

首先,我尝试:

interface Super
class A : Super
class B : Super

val a = if (System.currentTimeMillis() >= 100) A() else B()
我按了
Ctrl Q
来检查
a
的类型。正如预期的那样,它是超级的

但当我尝试时:

val someVar = if (System.currentTimeMillis() > 0) 1 else 1.0

它说
someVar
Any
。问题是:
Double
Int
都是
Number
compariable
的子类型,即它们有两个不同的超类型

如果您将示例更改为以下内容,您的变量也将是
Any
,因为
A
B
不再是
Super

interface Super
class A : Super, Serializable
class B : Super, Serializable

//a is of type Any
val a = if (System.currentTimeMillis() >= 100) A() else B()
如果希望变量的类型为
Number
,则可以显式声明变量的类型:

val someVar: Number = if (System.currentTimeMillis() > 0) 1 else 1.0

原因是,因为您的类只从一个接口继承。如果您查看
Int
Double

class Int : Number(), Comparable<Int>
class Double : Number(), Comparable<Double>

someVar
val someVar: Number = ...