Scala passing type parameters to object

后端 未结 4 1901
北恋
北恋 2021-02-20 09:11

In Scala v 2.7.7

I have a file with

class Something[T] extends Other

object Something extends OtherConstructor[Something]

This throws

4条回答
  •  孤城傲影
    2021-02-20 09:53

    You could use:

    object Something extends OtherConstructor[Something[_]]
    

    You will of course be restricted by having an existential type with no upper bound in place instead of a concrete type. This solution may not make sense and you might need one object per concrete type T, for those T's which you care about, e.g.

    object StringSomething extends OtherConstructor[Something[String]]
    

    But then this has the (possible) disadvantage that StringSomething is not the companion object of Something.

    However, my advice would be don't start messing about designing generic APIs (especially self-referential ones like the above) unless you really, really know what you are doing. It will almost certainly end in tears and there are plenty of CORE Java API's which are terrible because of the way generics have been added (the RowSorter API on JTable being one example)

提交回复
热议问题