【问题标题】:Does Aux pattern provides better typesafety then type parameter?Aux 模式是否提供比类型参数更好的类型安全性?
【发布时间】:2021-05-02 00:48:16
【问题描述】:

我围绕 Aux-pattern 进行了一些实验,发现 Aux 与编译器集成得更好。考虑以下两种情况:

我。

import Granularity.{Full, Partial}

sealed trait Granularity

object Granularity {

  case object Full extends Granularity

  sealed trait Partial extends Granularity {
    type GranularityKey
  }

  object Partial{
    type Aux[GK] = Partial{ type GranularityKey = GK }
  }
}

sealed trait TestBub{
  type G <: Granularity
}
object TestBub{
  type Aux[GG <: Granularity] = TestBub{ type G = GG }
  case class T1(i: Int) extends TestBub{
    type G = Full.type
  }
  case class T2[Gr](j: String) extends TestBub{
    type G = Partial.Aux[Gr]
  }

  def full[G <: Full.type](t: TestBub.Aux[G]): String = t match {
    case T1(i) => i.toString
  }
}

Scastie demo

这段代码编译良好没有警告

二。

import Granularity.{Full, Partial}

sealed trait Granularity

object Granularity {

  case object Full extends Granularity

  sealed trait Partial extends Granularity {
    type GranularityKey
  }

  object Partial{
    type Aux[GK] = Partial{ type GranularityKey = GK }
  }
}

sealed trait TestBub[G <: Granularity]

object TestBub{
  case class T1(i: Int) extends TestBub[Full.type]
  case class T2[Gr](j: String) extends TestBub[Partial.Aux[Gr]]

  def full[G <: Full.type](t: TestBub[G]): String = t match {
    case T1(i) => i.toString
  }
}

Scastie demo

此代码编译时带有警告。

match may not be exhaustive.
It would fail on the following input: T2(_)

问题:考虑到这两种情况,Aux 模式是否提供了一种更好的方式来对所有 ADT 分支的子集进行模式匹配?

【问题讨论】:

    标签: scala pattern-matching typesafe aux-pattern


    【解决方案1】:

    这是 Scala 2 类型系统的另一个问题。 Scala 3 在没有警告的情况下编译第二种情况(如预期的那样)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多