在scala中输入不匹配错误以便理解

时间:2016-09-13 02:00:04

标签: scala scalacheck

我正在为以下ADT编写生成器。想法是使用随机数据生成块。我在Type mismatch: expected: Seq[Field], actual:Gen[Field]方法中遇到编译器错误blockGen。我做错了什么?

修改

错误在此方法的最后一行fields,即yield Block(id, fields)

def blockGen(b: Block): Gen[Block] = for {
    id <- b.blockId
    fields <- b.fields.map(f => fieldGen(f))
} yield Block(id, fields)

ADT

trait Data {}

trait Field extends Data {
  val name: String
  val value: String
}

case class StringField(name: String, value: String) extends Field
case class NumberField(name: String, value: String) extends Field
case class Block(blockId: Field, fields: Seq[Field]) extends Data

发电机

def blockGen(b: Block): Gen[Block] = for {
    id <- b.blockId
    fields <- b.fields.map(f => fieldGen(f))
  } yield Block(id, fields)

def fieldGen(fieldType: Field): Gen[Field] = {
    for {
      f <-
      fieldType match {
        case _: NumberField => numGen
        case _: StringField => strGen
      }
    } yield f
  }

val strGen: Gen[StringField] = for {
    name <- Gen.identifier
    value <- Gen.alphaStr
  } yield StringField(name, value)

val numGen: Gen[NumberField] = for {
    name <- Gen.identifier
    value <- Gen.numStr
  } yield NumberField(name, value)

1 个答案:

答案 0 :(得分:4)

这是由:fieldGen(f)返回类型为Gen[Field],但您的Block fields类型为Seq[Field],因此编译器抛出type mismatch

解决方案:

  1. def fieldGen(fieldType: Field): Gen[Field]更改为def fieldGen(fieldType: Field): Seq[Field],或将Block字段更改为Gen[Feild]
  2. Gen创建隐式转换为Seq,例如:

    implicit def genToSeq[T](s: Gen[T]): Seq[T] = ??? // implementation conversion.