我有一组类型,每个类型都有自己的类型成员:
sealed trait FieldType {
type Data
def parse(in: String): Option[Data]
}
object Name extends FieldType {
type Data = String
def parse(in: String) = Some(in)
}
object Age extends FieldType {
type Data = Int
def parse(in: String) = try { Some(in.toInt) } catch { case _ => None }
}
Run Code Online (Sandbox Code Playgroud)
我有一组在FieldTypes的集合上运行的类型(使用样板而不是抽象的arity):
sealed trait Schema {
type Schema <: Product
type Data <: Product
val schema: Schema
def read(in: Seq[String]): Option[Data]
}
trait Schema1 extends Schema {
type D1
type FT1 <: FieldType { type Data = D1 }
type Schema = Tuple1[FT1]
type Data = Tuple1[D1]
def read(in: Seq[String]) = schema._1.parse(in(0)).map(Tuple1.apply)
}
trait Schema2 extends Schema {
type D1
type D2
type FT1 <: FieldType { type Data = D1 }
type FT2 <: FieldType { type Data = D2 }
type Schema = (FT1, FT2)
type Data = (D1, D2)
def read(in: Seq[String]) = {
for {
f <- schema._1.parse(in(0))
s <- schema._2.parse(in(1))
} yield (f, s)
}
}
Run Code Online (Sandbox Code Playgroud)
我以为我可以使用这个系统来优雅地定义有意义的字段集,因为scala能够推断出类型成员:
class Person extends Schema2 {
val schema = (Name, Age)
}
Run Code Online (Sandbox Code Playgroud)
但是,这不编译!我必须包含所有类型成员的定义:
class Person extends Schema2 {
type D1 = String; type D2 = Int
type FT1 = Name.type; type FT2 = Age.type
val schema = (Name, Age)
}
Run Code Online (Sandbox Code Playgroud)
scala怎么不能推断D1,...和FT1,...?我怎样才能重构这个,所以我不必指定类型变量Person?
注意:一旦我对宏有了更好的理解,我打算将它们用于Schema类型.而且,我宁愿不使用无形.这是一个很棒的图书馆,但我不想把它拉进来解决这个问题.
通过声明:
val schema: Schema
Run Code Online (Sandbox Code Playgroud)
您指定schema必须是类型Schema 或其任何子类型.因此,知道的类型schema,你无法推断Schema,因为它可能是任何超类型的schema.type.
您可以通过完全颠倒事物来解决您的问题:根据以下方面定义类型别名schema.type:
trait Schema2 extends Schema {
type Schema = (FieldType, FieldType)
type FT1 = schema._1.type
type FT2 = schema._2.type
type D1 = FT1#Data
type D2 = FT2#Data
type Data = (D1, D2)
def read(in: Seq[String]) = {
for {
f <- schema._1.parse(in(0))
s <- schema._2.parse(in(1))
} yield (f, s)
}
}
Run Code Online (Sandbox Code Playgroud)
(不确定它是否真的有效,但理论上这应该是检查.)