creating a new instance of a type in scala

后端 未结 3 1151
春和景丽
春和景丽 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:22

    The same as @Raphael's answer with a case class's apply method:

    class Container[A](contained: A)
    case class Person(name: String)
    case class PersonContainer(person: Person) extends Container[Person](person)
    implicit def _ = PersonContainer.apply _
    
    class Creator {
      def deserializeAndPackage[A, B <: Container[A]](data: Array[Byte])
                               (implicit containerCreator: (A => B)): B = {
        val p = /* deserialize data as type of A */
        containerCreator(p)
      }
    }
    

提交回复
热议问题