abatyuk
abatyuk

Reputation: 1342

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.

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:

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, i.e. 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:

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?

Upvotes: 0

Views: 90

Answers (1)

dwickern
dwickern

Reputation: 3519

You don't use the type T in your examples, and getting rid of it would fix your type inference issue:

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

Upvotes: 2

Related Questions