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
}
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.