Scala:如何强制提供类型
假设我们有以下特征和类定义Scala:如何强制提供类型,scala,type-inference,scala-generics,Scala,Type Inference,Scala Generics,假设我们有以下特征和类定义 trait Model extends Product class X[T <: Model] {} 编译器没有抱怨。在这种情况下,推断的类型是Nothing。我想知道如何在编译时防止出现这种情况,以便在不提供显式类型的情况下不允许创建X的实例,即作为模型的子类型?我认为这是可行的: trait Model case class M() extends Model // one subclass of Model, for testing // use im
trait Model extends Product
class X[T <: Model] {}
编译器没有抱怨。在这种情况下,推断的类型是Nothing
。我想知道如何在编译时防止出现这种情况,以便在不提供显式类型的情况下不允许创建X的实例,即作为模型的子类型?我认为这是可行的:
trait Model
case class M() extends Model // one subclass of Model, for testing
// use implicit to force T to be convertible to Model
// which works for actual Model subclasses but not Nothing
class X[T<:Model](implicit f: (T) => Model)
new X
error: type mismatch;
found : <:<[Nothing,Nothing]
required: T => Model
new X[M] // ok
我同意上面的观点,但另一个想法是显式地将模型子类的类作为参数传递:
classx[Tclassx[T我喜欢这个想法,但我不确定它是否符合OP的期望:new X
制作了一个X[Model]
@Juh_u。这不是OP想要的吗?我想他想要的类型是明确的,也就是说,你不能写new X
是的,不是我想要的,但我喜欢这个想法,所以投票吧。
trait Model
case class M() extends Model // one subclass of Model, for testing
// use implicit to force T to be convertible to Model
// which works for actual Model subclasses but not Nothing
class X[T<:Model](implicit f: (T) => Model)
new X
error: type mismatch;
found : <:<[Nothing,Nothing]
required: T => Model
new X[M] // ok
new X[Nothing] // ok
class X[T<:Model](tClass: Class[T])
new X(classOf[M]) // ok
new X(classOf[Nothing])
error: type mismatch;
found : Class[Nothing](classOf[scala.Nothing])
required: Class[T]
Note: Nothing <: T, but Java-defined class Class is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: T`. (SLS 3.2.10)
class X[-T <: Model] {}
val x = new X
x: X[Model] = X@7c9bdee9