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 = ...