2017-03-17 19 views
2

我使用Scala的播放2.5.X和需要確定與需要映射即斯卡拉播放形式:無法找到枚舉亞型格式化類型的類

object OptionType extends Enumeration { 
    type Type = Value 
    val Call = Value("Call") 
    val Put = Value("Put") 
    val Straddle = Value("Straddle") 
} 

case class MyParameters(impliedVolSpread: Double, optionType: OptionType.Type) 

@Singleton 
class MyForm @Inject()(implicit val messagesApi: MessagesApi) { 
    val Instance = Form { 
    mapping(
     "impliedVolSpread" -> of[Double], 
     "optionType" -> of[OptionType.Type], 
    )(MyParameters.apply)(MyParameters.unapply) 
    } 
} 

enum類型表單但是這會導致編譯器錯誤:

Cannot find Formatter type class for OptionType.Type. 
Perhaps you will need to import play.api.data.format.Formats._ 

會比其他類似的問題後,我以爲這個用例已經解決了如Enum Mapper PR 240

回答

2

自認爲公關是不是仍然可以在Scala中播放2.5.10我偷了我需要的比特和結束是這樣的:

import play.api.data._ 
import play.api.data.format._ 
import play.api.data.Forms._ 

object EnumPlayUtils { 
    //------------------------------------------------------------------------ 
    // public 
    //------------------------------------------------------------------------ 
    /** 
    * Constructs a simple mapping for a text field (mapped as `scala.Enumeration`) 
    * 
    * For example: 
    * {{{ 
    * Form("gender" -> enum(Gender)) 
    * }}} 
    * 
    * @param enum the enumeration 
    */ 
    def enum[E <: Enumeration](enum: E): Mapping[E#Value] = of(enumFormat(enum)) 

    /** 
    * Default formatter for `scala.Enumeration` 
    * 
    */ 
    def enumFormat[E <: Enumeration](enum: E): Formatter[E#Value] = new Formatter[E#Value] { 
    def bind(key: String, data: Map[String, String]) = { 
     Formats.stringFormat.bind(key, data).right.flatMap { s => 
     scala.util.control.Exception.allCatch[E#Value] 
      .either(enum.withName(s)) 
      .left.map(e => Seq(FormError(key, "error.enum", Nil))) 
     } 
    } 

    def unbind(key: String, value: E#Value) = Map(key -> value.toString) 
    } 
} 

像這樣使用:

@Singleton 
class MyForm @Inject()(implicit val messagesApi: MessagesApi) { 

    import EnumPlayUtils._ 

    val Instance = Form { 
     mapping(
      "impliedVolSpread" -> of[Double], 
      "optionType" -> enum(OptionType), 
     )(MyParameters.apply)(MyParameters.unapply) 
    } 
}