考虑这段代码:
val foo = if(true)
new java.lang.Double(4)
else
new java.lang.Integer(4)
foo
的推断类型是:
Number with Comparable[_ >: Double with Integer <: Number with
Comparable[_ >: Double with Integer <: Number]]
所以基本上编译器在边界上循环并在第三次递归后中止。
为什么以下内容还不够?
Number with Comparable[_ >: Double with Integer <: Number]
最佳答案
不是答案,而是在 REPL 中隐式使用的一些线索。编译器认为类型不同。推断的类型更加具体:
// some type aliases to make reading easier
type Dx = java.lang.Double
type Ix = java.lang.Integer
// the type the compiler came up with:
type Inferred = Number with Comparable[
_ >: Dx with Ix <: Number with Comparable[_ >: Dx with Ix <: Number]]
// your type:
type Soc = Number with Comparable[_ >: Dx with Ix <: Number]
检查我是否正确使用了类型别名:
val d = new java.lang.Double(4)
val i = new java.lang.Integer(4)
val foo: Soc = if (true) d else i
// foo: Soc = 4.0
val foo: Inferred = if (true) d else i
// foo: Inferred = 4.0
类型不相同:
implicitly[Soc =:= Inferred] // error
您的类型是推断类型的父类(super class)型:
implicitly[Inferred <:< Soc] // ok
implicitly[Soc <:< Inferred] // error
因此,根据编译器的说法,它提出了一个更具体的类型 - 这将是正确的做法。请注意,可以像这样重新创建用例:
class N // like java.lang.Number
trait C[T] // like Comparable
class I extends N with C[I] // like java.lang.Integer
class D extends N with C[D] // like java.lang.Double
type DI = N with C[_ >: D with I <: N with C[_ >: D with I <: N]]
// DI is like the type inferred
type DI_SOC = N with C[_ >: D with I <: N] // your type
val foo: DI = if (true) new D else new I // ok
val foo: DI_SOC = if (true) new D else new I // ok
implicitly[DI =:= DI_SOC] // error
implicitly[DI <:< DI_SOC] // DI_SOC super type of DI
implicitly[DI_SOC <:< DI] // error
所以我想知道我们是否可以创建一个类 DI_SOC
但不是DI
,这将说明DI
和DI_SOC
类型不同,并且您的类型不是最小上限。
好的,在离开计算机一段时间后再次尝试。这是一个类 DI_SOC
但不是DI
:
class A extends N with C[N]
implicitly[A <:< DI_SOC] // ok
implicitly[A <:< DI] // error
应用于原始用例:
class Ax extends Number with Comparable[Number] {
def doubleValue() = 0d
def floatValue() = 0f
def intValue() = 0
def longValue() = 0L
def compareTo(n: Number) = 0
}
implicitly[Ax <:< Soc] // ok
implicitly[Ax <:< Inferred] // error
因此,类型 Soc
和Inferred
和Ax
不相同证明Number with Comparable[_ >: Double with Integer <: Number]
是不是最小上限...
换句话说,Double with Integer <: ? <: Number
之间有一些空间。但 Double with Integer <: ? <: Number with Comparable[_ >: Double with Integer <: Number]
之间不多
关于generics - 为什么 java.lang.Integer 和 java.lang.Double 的最小上限被推断为非循环类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8109105/