Lena Bru Lena Bru - 16 days ago 8
Scala Question

How to define this class

I have a Scala + Java project.

In the java classes I needed 2 classes that extend from the same class, and their usage is defined in scala.

So I have this class

public class BaseUser {

int id;
private String name;
public BaseUser withName(String name){
this.name = name;
return this;
}


}


and the extended class

public SpecificUser extends BaseUser {

//inherit default for now
}


Then in scala I have a definition of a DAO

trait BaseUserDao {

def insertUser(user:BaseUser) : Boolean

}


class SpecificUserDao extends UserDao{

def insertUser(user : SpecificUser) : Boolean = {
db.insert(user).isDefined
}
}


But this does not compile, it says that i have to implement insertUser(user:BaseUser) instead of SpecificUser

How do I define it so that i can create an implementation per user type ?

Answer

Change your implementation to something as shown below. Have a type parameter T whose upper bound is BaseUser. In the declaration of SpecificUserDao just make the T SpecificUser.

trait BaseUserDao[T <: BaseUser] {
  def insertUser(user: T) : Boolean
}

class SpecificUserDao[SpecificUser]  extends BaseUserDao[SpecificUser] {
  override def insertUser(user: SpecificUser): Boolean = ???
}

Or you can declare the type T inside the trait.

trait BaseUserDao {
  type T <: BaseUser
  def insertUser(user: T) : Boolean
}

class SpecificUserDao  extends BaseUserDao {
  override type T = SpecificUser
  override def insertUser(user: SpecificUser): Boolean = ???
}