簡體   English   中英

類型推斷錯誤,帶有多個類型參數且無

[英]Type inference error with multiple type parameters and Nothing

我正在嘗試為表示屬性的ADT建模,並能夠設置默認值。

因此,我的類型定義如下,因此我可以在類型上進行模式匹配:

trait PropertyType[U] {
  def typeName: String
}

case object OInt32 extends PropertyType[Int] {
  override def typeName: String = "Edm.Int32"
}

case object OString extends PropertyType[String] {
  override def typeName: String = "Edm.String"
}

現在,屬性本身由PropertyType及其參數進行參數化:

case class Property[T <: PropertyType[U], U](name: String,
                                             propertyType: T,
                                             nullable: Boolean = true,
                                             maxLength: Option[Integer] = None,
                                             defaultValue: Option[U] = None)

如果兩個參數都存在,則類型推斷工作正常,即以下代碼可以正常編譯:

  val intProp = Property("Integer", propertyType = OInt32, defaultValue = Some(123))
  val stringProp = Property("String", propertyType = OString, defaultValue = Some("123"))

另外,它防止我嘗試為指定的類型設置錯誤的默認值,因此以下內容將無法編譯。

val stringProp = Property("String", propertyType = OString, defaultValue = Some(123))

我遇到的問題是,如果我忽略默認值或將其設置為None,則編譯將失敗,因為無法推斷出U型:

val stringPropWithDefault = Property("String", propertyType = OString) //Doesn't compile
val stringPropWithDefault = Property[OString.type, String]("String", propertyType = OString) //Compiles

如果只有一個參數,scala編譯器可以推斷類型嗎?

您無需在示例中使用類型T,而將其刪除將解決您的類型推斷問題:

case class Property[U](name: String,
                       propertyType: PropertyType[U],
                       nullable: Boolean = true,
                       maxLength: Option[Integer] = None,
                       defaultValue: Option[U] = None)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM