Kotlin:“val someVar = if(xx)1 else 1.0”,为什么someVar是“Any”?
首先,我试过:
interface Super class A : Super class B : Super val a = if (System.currentTimeMillis() >= 100) A() else B()
我按Ctrl Q
来检查一个类型。 Super
预期的。
但是当我尝试:
val someVar = if (System.currentTimeMillis() > 0) 1 else 1.0
它说一些someVar
是一个Any
。 它不应该是一个Number
吗?
原因是,因为你的类只是从一个单一的接口继承。 如果你看看Int
和Double
class Int : Number(), Comparable<Int> class Double : Number(), Comparable<Double>
所以不能确定使用哪种通用类型。
在这种情况下,你必须通过明确的类型
val someVar: Number = ...
问题是 : Double
和Int
都是Number
和 Comparable
子类型,即它们有两种不同的超类型。
如果您将示例更改为以下内容,那么您的变量也将是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