Scala F-limited polymorphism at the facility

I cannot write the following F-bounded polymorphism in Scala. Why?

trait X[T <: X[T]] object Y extends X[Y] 

How can I express this and compile it?

+6
source share
2 answers

It seems that you should write,

 trait X[T <: X[T]] object Y extends X[Y.type] 

however, if you try to have the compiler provide you with a useless (and I think false) error,

 scala> object Y extends X[Y.type] <console>:16: error: illegal cyclic reference involving object Y object Y extends X[Y.type] 

I say β€œfalse” because we can build an equivalent facility with a little extra infrastructure,

 trait X[T <: X[T]] trait Fix { type Ytype >: Y.type <: Y.type; object Y extends X[Ytype] } object Fix extends Fix { type Ytype = Y.type } import Fix.Y 

If you want to experiment with this in real code, using a package object Fix instead of object Fix will make this idiom more convenient.

+7
source

Change it to:

  trait Y extends X[Y] 

object not a type in Scala, but the so-called companion object. By defining object Y , you cannot express that it must extend trait T[Y] , since the second Y is of type Y that has not been defined. However, you can do the following:

 trait Y extends X[Y] //If you try this on the REPL, do :paste before object Y extends X[Y] 

In this case, the object Y extends X[Y] , where the second Y is the characteristic that you just defined, make sure that you remember it.

+1
source

All Articles