type parameter in traits to define data types in scala

时间:2017-08-05 11:01:33

标签: scala

I am new to scala and want to create a model class for a message .Message are comprisedoing of tag as key with value and value can be a string with specified length,int or a enumeration

tag     value
100      a    
200      b      constraint of length =45
300      0,1,2

where 0-new 1-amend 2- cancel

 trait ElementType  {
    type A
    type length
}


    case class Tag() extends ElementType {
      override type A = this.type

     }

  case class Value() extends ElementType{
     override type A = this.type
     override type length = this.type
    }

case class Message(
     messageId:MessageId
  )

case class MessageId(tag: Tag[Int], value: Value[String]){
  override def toString = tag + "=" + value + 1.toChar
 }

I am getting compile error in MessageId,is there a better way to write the code

1 个答案:

答案 0 :(得分:0)

我猜你的问题是MessageId它指的是Tag[Int]Value[String],它们没有通用参数。

尝试类似这样的内容,但我认为您还需要重新定义TagValue类:

case class MessageId(tag: Tag{type A = Int}, value: Value{type A = String}){
  override def toString = tag + "=" + value + 1.toChar
}

由于您似乎想将它们用作泛型,我会尝试这样的事情:

sealed trait ElementType[+A] {
    def length: Int
}

sealed trait Tag extends ElementType[Int] {
    override def length: Int = 0
}
case object Tag100 extends Tag
case object Tag200 extends Tag
case object Tag300 extends Tag

sealed trait Value[+A] extends ElementType[A] {
    override def length: Int = 0
}

final case class Value100(a: String) extends Value[String] {
    override def length: Int = a.length
}
final case class Value200(b: String) extends Value[String] {
    require(b.length <= length)
    override def length: Int = 45
}
case object Value300One extends Value[Nothing]
case object Value300Two extends Value[Nothing]
case object Value300Three extends Value[Nothing]

case class Message(
    messageId:MessageId
)

case class MessageId(tag: Tag, value: Value[String]){
    override def toString = tag + "=" + value + 1.toChar
}
+中的{p> [+A]表示该类型将是协变的,因此如果QR的子类型,则ElementType[Q]是{{1}的子类型}}。 (这是ElementType[R]与任何Tag兼容所必需的(因此它会扩展到极端ElementType)。)

ElementType[Nothing]的用例对我来说并不清楚。如果您希望它是编译时约束,请在Shapeless'Sizedan example上使用它。