Passing a type parameter for instantiation

后端 未结 2 1578
清歌不尽
清歌不尽 2021-01-24 15:02

Why wouldn\'t the scala compiler dig this:

class Clazz

class Foo[C <: Clazz] {
  val foo = new C  
}

class type required but C found
[error]   val a = new C         


        
2条回答
  •  -上瘾入骨i
    2021-01-24 15:35

    This is a classic generic problem that also happens in Java - you cannot create an instance of a generic type variable. What you can do in Scala to fix this, however, is to introduce a type evidence to your type parameter that captures the runtime type:

    class Foo[C <: Clazz](implicit ct: ClassTag[C]) {
        val foo = ct.runtimeClass.newInstance
    }
    

    Note that this only works if the class has a constructor without any arguments. Since the parameter is implicit, you don't need to pass it when calling the Foo constructor:

    Foo[Clazz]()
    

提交回复
热议问题