从一开始就不确定我是否有解决问题的正确方法。我在这里寻找两个不同的答案:
我希望动态(最终在运行时)向其添加不同属性的“事物”。例如 “文档”事物可能具有“地址”属性。另一个“文档”内容可能 具有“发送电子邮件地址”属性。第三个“文档”内容可能同时具有这两个属性。
下面的代码显示了Contained(可能表示各种事物)和Thing(其中的一种)。
它还包含两个HigherKindedType特性,它们是我希望动态添加到Contained事物中的属性。
我无法在“ ContainedOps”类中创建一种“带有属性的任意类型”。
请帮助我完成???零件。
package example
import scala.language.higherKinds
trait Contained[A]
case class Thing(id: String) extends Contained[Thing]
//case class Attribute(value: String) // needed ?
trait WithAttribute[F[_]] {
def attribute[A, B](fa: F[A])(f: A => B) : F[B]
}
trait WithAnotherAttribute[F[_]] {
def anotherAttribute[A, B](fa: F[A])(f: A => B) : F[B]
}
object Contained {
implicit class ContainedOps[A](c: Contained[A]) {
type AWithAttribute = A with WithAttribute[Contained]
def withAttribute(value: String): AWithAttribute = ???
type AWithAnotherAttribute = A with WithAnotherAttribute[Contained]
def withAnotherAttribute(value: String): AWithAnotherAttribute = ???
}
}
object Example extends App {
val thing = Thing("one")
println(s"thing: $thing")
val thingWithAttribute = thing.withAttribute("attributeValue")
println(s"thingWithAttribute: $thingWithAttribute")
val thingWithAnotherAttribute = thing.withAnotherAttribute("anotherAttributeValue")
println(s"thingWithAnotherAttribute: $thingWithAnotherAttribute")
val thingWithAttributeWithAnotherAttribute = thingWithAttribute.withAnotherAttribute("anotherAttributeValue")
println(s"thingWithAttributeWithAnotherAttribute: $thingWithAttributeWithAnotherAttribute")
}
答案 0 :(得分:1)
Scala类型是在编译时定义的,并且在运行时是静态的,因此“动态创建[]类型”是不可启动的。