2016-09-13 168 views
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) 
+0

什麼線生成該消息? (顯然,問題是什麼標識符的類型不匹配) – GreenAsJade

+0

@GreenAsJade添加違規行。請參見編輯部分 –

+1

'fields'是'Seq [Gen [Field]]'的一個_element_,即'Gen [Field]',而'Block'構造函數期望'Seq [Field]'' –

回答

4

這是造成:fieldGen(f)返回類型爲Gen[Field],但你的Blockfields類型是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.