How do I create an instance of a trait in a generic method in scala?

前端 未结 2 1178
暗喜
暗喜 2020-12-05 21:25

I\'m trying to create an instance of a trait using this method

val inst = new Object with MyTrait

This works well, but I\'d like to move th

2条回答
  •  一向
    一向 (楼主)
    2020-12-05 21:57

    You can't do this (even with a Manifest). The code new Object with T involves creating a new anonymous class representing the combination of Object with T. To pass this to your create function, you would have to generate this new class (with new bytecode) at runtime, and Scala has no facilities for generating a new class at runtime.

    One strategy might be to try to transfer the special functionality of the factory method into the class's constructor instead, and then use the constructor directly.

    Another possible strategy is to create conversion functions (implicit or otherwise) to the traits you're interested in using with this class.

提交回复
热议问题