Use a shapeless mapper without specifying the type of result

This seems to be a classic question for developers used for programming like Scala, but I couldn't find (or don't know how to look for) a solution or template for this. Suppose I have a class like this:

abstract class TypedTest[Args <: HList](implicit val optMapper: Mapped[Args, Option]) {
  type OptArgs = optMapper.Out

  def options: OptArgs // to be implemented by subclasses
}

I want users of this class to create an instance with a type parameter HList( Args), and the class provides a method to get an instance HListcontaining an instance of each specified type inside Option( OptArgs). For this, I use the shapeless Mapped type. Please note that I do not have an instance Argsto provide during instance creation.

This code does not work, because the compiler does not output a specific type OptArgsand even an explicitly correct implementation, such as def options = HNil, gives a compilation error. The same code using the Aux pattern:

abstract class TypedTest[Args <: HList, OptArgs <: HList](implicit val optMapper: Mapped.Aux[Args, Option, OptArgs]) {
  def options: OptArgs
}

This forces me to specify both lists when creating the instance, which makes the external API unnecessary to verbose. Is there a workaround for this?

+4
source share
1 answer

This is my understanding, but I am not 100% sure and will be happy to stand corrected.

TypedTest.OptArgs , . TypedTest - Mapped[Args, Option].Out, , . , OptArgs .

Mapped.Aux Out0 , IIUC, :

abstract class TypedTest[Args <: HList](
    implicit val optMapper: Mapped.Aux[Args, Option, T] forSome { type T }) {

  type OptArgs = optMapper.Out

  def options: OptArgs // to be implemented by subclasses
}

val intTest = new TypedTest[Int :: HNil] {
  def options = Some(1) :: HNil
}

Error:(18, 29) type mismatch;
found   : shapeless.::[Some[Int],shapeless.HNil]
required: this.OptArgs
  (which expands to)  T
    def options = Some(1) :: HNil

, - , Out OptArgs .

0

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


All Articles