Scala Type Based Attribute Extractor - Getter Lens Only?

What is the best way to retrieve a type from a data container, such as the case class.

For example, if I have a tagged tag type Tagged[U] = { type Tag = U} trait PIDthat is an Int tag type ProductId = Int with Tagged[PID]or scalaz style type ProductId = Int @@ PIDand says other fields in the product type Name = String @@ PName, etc. and a data container that contains product attributes;

case class Product(pid: ProductId, name: Name, weight: Weight)

How could I write a general erase method A => Bwithout resorting to reflection?

The reason is because I want to dynamically retrieve a field from the Product container at runtime. That is, the user passes the attribute of the product that they want to retrieve.

those. if I want to dynamically get ProductId, I can write a method that takes a type and returns a value, for example.

trait Extractor[A] {
  def extract[B](i: A): B = //get type B from the Product class
}

.

, A = > B ;

trait Getter[A, B] {
  def extract(i: A): B
}
//... mix this in...
trait GetPID extends Getter[Product, ProductId] {
  override def extract(implicit i: Product) = i.pid
}
trait GetName extends Getter[Product, Name] {
  override def extract(implicit i: Product) = i.name
}

, .

val dyn = new DynamicProductExtractor with GetPID 
dyn.extract

.

- Lens.

+4
1

, :

import shapeless._, tag._

trait PID; trait PName; trait PWeight

type ProductId = Int @@ PID
type Name = String @@ PName
type Weight = Double @@ PWeight

case class Product(pid: ProductId, name: Name, weight: Weight)

val pid = tag[PID](13)
val name = tag[PName]("foo")
val weight = tag[PWeight](100.0)

val product = Product(pid, name, weight)

Shapeless, Scalaz Tagged. , , case, Shapeless Generic:

import ops.hlist.Selector

def extract[A] = new {
  def from[C, Repr <: HList](c: C)(implicit
    gen: Generic.Aux[C, Repr],
    sel: Selector[Repr, A]
  ) = sel(gen.to(c))
}

, , , .

:

scala> extract[ProductId].from(product)
res0: Int with shapeless.tag.Tagged[PID] = 13

, case , . (, - extract[Char] from(product)), .

, - , (, Shapeless ).

( , "", , case, , , .)

+8

All Articles