Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

scala - Does Aux pattern provides better typesafety then type parameter?

I was running some experiments around Aux-pattern and figured out that Aux is somewhat better integrated with compiler. Consider the following two cases:

I.

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

This code compiles fine with no warning.

II.

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

This code compiles with a warning.

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

QUESTION: Taking these two cases into account does Aux pattern provide a better way to pattern match on a subset of all ADT branches?

question from:https://stackoverflow.com/questions/65931782/does-aux-pattern-provides-better-typesafety-then-type-parameter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is yet another problem with Scala 2 typesystem. Scala 3 compiles the second case with no warnings (as expected).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...