Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bounded generics in Scala (as <E extends MyClass> in Java )

Tags:

generics

scala

I'm migrating an app from java to Scala. In java I have somethng like

abstract class CommonObjectInfo{//...}
class ConcreteObject extends CommonObjectInfo{//...}

abstract class AbstractWrapper<E extends CommonObjectInfo>{//...} 
class ConcreteWrapper extends CommonObjectInfo<ConcreteObject>{//...} 

How can I express formally the "wrappers" objects in Scala? I

like image 266
JayZee Avatar asked Oct 17 '11 10:10

JayZee


2 Answers

abstract class CommonObjectInfo
class ConcreteObject extends CommonObjectInfo

abstract class AbstractWrapper[E <: CommonObjectInfo]
class ConcreteWrapper extends AbstractWrapper[ConcreteObject]
like image 50
agilesteel Avatar answered Sep 29 '22 23:09

agilesteel


The usual solution is the one from agilesteel, but sometimes it's useful to pull the type information "inside" the class (especially when the type in question is considered to be an implementation detail):

abstract class CommonObjectInfo

class ConcreteObject extends CommonObjectInfo

abstract class AbstractWrapper{
 type objectInfo <: CommonObjectInfo
}

class ConcreteWrapper {
  type objectInfo = ConcreteObject 
}
like image 31
Landei Avatar answered Sep 29 '22 23:09

Landei