簡體   English   中英

為什么java.lang.Integer和java.lang.Double的最小上限被推斷為非循環類型?

[英]Why is the least upper bound of java.lang.Integer and java.lang.Double inferred as a acyclic type?

考慮以下代碼:

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

您的類型是推斷類型的超類型:

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 ,這將說明DIDI_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

因此, SocInferred類型一樣, Ax證明Number with Comparable[_ >: Double with Integer <: Number] 不是最小上限...

換句話說, Double with Integer <: ? <: Number之間有一些空間Double with Integer <: ? <: Number Double with Integer <: ? <: Number Double with Integer <: ? <: Number with Comparable[_ >: Double with Integer <: Number]之間的Double with Integer <: ? <: Number但不多Double with Integer <: ? <: Number with Comparable[_ >: Double with Integer <: Number] Double with Integer <: ? <: Number with Comparable[_ >: Double with Integer <: Number]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM