Clala Variance Clarification and Type Limitations Required

I have a scala trait defined as follows:

trait AdvertisementDAO[A <: Advertisement] extends CrudRepository[A, Integer] { ... 

I would like to be able to get an instance of this DAO that will work for both subclasses of advertising and the base class of advertising . I am not sure how to achieve the desired effect.

Here is what I tried:

 @Inject var advertisementDAO: AdvertisementDAO[+Advertisement] = _ 

Can anyone help?

+4
source share
2 answers

It looks like you are trying to define a parameter of type, A, sign, AdvertisementDAO, as covariant. Below is a sample code example from the previous answer using the covariance annotation +.

 trait Advertisement {} class AdvertisementImpl extends Advertisement{} class CrudRepository[+A,B] {} trait AdvertisementDAO[+A <: Advertisement] extends CrudRepository[A, Integer] {} class AdvertisementDAOImpl[+A <: Advertisement] extends AdvertisementDAO[A]{} class AdvertisementDAOImpl2 extends AdvertisementDAO[AdvertisementImpl]{} class AdvertisementDAOImpl3 extends AdvertisementDAO[Advertisement]{} object Tester { def main(args:Array[String]):Unit = { var advertisementDAO: AdvertisementDAO[Advertisement] = null advertisementDAO = new AdvertisementDAOImpl advertisementDAO = new AdvertisementDAOImpl2 advertisementDAO = new AdvertisementDAOImpl3 } } 

Another example of a covariant common is scala.collection.immutable.List. Defining a common (class or trait) C as covariant means that C [S] is a subtype of C [T] if type S is a subtype of type T. For example, AdvertisementDAO [AdvertisementImpl] is a subtype of AdvertisementDAO [Advertising] because AdvertisementImpl is a subtype advertising (as AdvertisingImpl expands advertising). I published an article that contains a tutorial on dispersion, as it happens in many languages ​​(e.g. Scala, C #, Java). Slides are also available for a quick overview. Hope this helps.

+3
source

I tried many combinations, but I get one that compiles with scala 2.9.1

  var advertisementDAO: AdvertisementDAO[_ <:Advertisement] = _ advertisementDAO = new AdvertisementDAOImpl advertisementDAO = new AdvertisementDAOImpl2 advertisementDAO = new AdvertisementDAOImpl3 

My code is:

 trait Advertisement {} class AdvertisementImpl extends Advertisement{} class CrudRepository[A,B] {} trait AdvertisementDAO[ A <: Advertisement] extends CrudRepository[A, Integer] {} class AdvertisementDAOImpl[A <: Advertisement] extends AdvertisementDAO[A]{} class AdvertisementDAOImpl2 extends AdvertisementDAO[AdvertisementImpl]{} class AdvertisementDAOImpl3 extends AdvertisementDAO[Advertisement]{} 
+2
source

Source: https://habr.com/ru/post/1399825/


All Articles