简体   繁体   English

类型推断错误,带有多个类型参数且无

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

I am trying to model a ADT for representing properties, with ability to set default value. 我正在尝试为表示属性的ADT建模,并能够设置默认值。

So, my type definition is the following, so i can pattern match on the type: 因此,我的类型定义如下,因此我可以在类型上进行模式匹配:

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"
}

Now, the property itself is parameterized by the PropertyType as well as its parameter: 现在,属性本身由PropertyType及其参数进行参数化:

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

Type inference works fine if both parameters are present, ie the following code compiles fine: 如果两个参数都存在,则类型推断工作正常,即以下代码可以正常编译:

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

Also, it prevents me from trying to set wrong default value for the specified type, so the following will not compile. 另外,它防止我尝试为指定的类型设置错误的默认值,因此以下内容将无法编译。

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

The issue i'm having with inference that if I omit default value or set it to None, compilation fails as type U cannot be inferred: 我遇到的问题是,如果我忽略默认值或将其设置为None,则编译将失败,因为无法推断出U型:

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

Can scala compiler infer type if only one parameter is present? 如果只有一个参数,scala编译器可以推断类型吗?

You don't use the type T in your examples, and getting rid of it would fix your type inference issue: 您无需在示例中使用类型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