3
我正在爲以下ADT編寫生成器。想法是用隨機數據生成塊。我在blockGen
方法中遇到編譯器錯誤Type mismatch: expected: Seq[Field], actual:Gen[Field]
。我究竟做錯了什麼?類型不匹配錯誤scala理解
EDIT
錯誤與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)
什麼線生成該消息? (顯然,問題是什麼標識符的類型不匹配) – GreenAsJade
@GreenAsJade添加違規行。請參見編輯部分 –
'fields'是'Seq [Gen [Field]]'的一個_element_,即'Gen [Field]',而'Block'構造函數期望'Seq [Field]'' –