creating a new instance of a type in scala

后端 未结 3 1142
春和景丽
春和景丽 2021-02-04 13:41

If I have a class C defined as

class C[A]

is there any way to create a new instance of A within C? Something like



        
3条回答
  •  醉梦人生
    2021-02-04 14:11

    You can demand an implicit parameter, like so:

    class A[T](implicit newT : T) { 
      val t = newT 
    } 
    

    All you need then is to have an implicit factory of the desired type in scope when you instanciate A, e.g. the following works:

    implicit def newSeq[T] = Seq[T]()                
    val a = new A[Seq[String]]                            
    

    As shown by:

    scala> a.t
    res22: Seq[String] = List()
    

提交回复
热议问题