Scala type type to get the most specific type for an element type

Consider the following Scala code:

trait Elem
class MyElem extends Elem

trait Holder {
  type EP <: Elem
  def get: EP
}

class MyHolder(e: MyElem) extends Holder {
  type EP = MyElem
  def get = e
}

Depending on whether I have an object typed in Holderor MyHolder, the call getmay return Elemor MyElem, respectively. I am trying to make this information available at the level level, but I am not getting any results. Consider, for example, a type class Getteras follows:

trait Getter[From] {
  type Out
  def get(from: From): Out
}

object Getter {
  type Aux[From, Out0] = Getter[From] { type Out = Out0 }

  def apply[From](implicit getter: Getter[From]): Getter.Aux[From, getter.Out] = getter

  // some way to create a `Getter[H <: Holder]`
  // where `Out` is the most specific type known for `H#EC`
}

Getter[MyHolder] // should return a MyHolder { type Out = MyElem }
Getter[Holder] // should return a Holder { type Out = Elem }

I am trying to create an implicit constructor for Getter[H <: Holder]that is not in the fragment, but even if I tried several methods of type restriction, I do not get any results that work for both examples above.

Can this be done using the Scala compiler? Does this type class help me shapelessor scalaz?

+4
1

, ,

- , - /, :

val x: Holder#EP = ???

, , , , .

0

Source: https://habr.com/ru/post/1675563/


All Articles