Reputation: 23
I am not sure whether the way I designed the project was correct.
My child classes have similar logics (functions), hence I would like to extract those similar logics into the parent class, and make them extend the parent class. However, although they have similar logic, they are dealing with Scala Collection of different element types: Map[String, String], Map[String, String], Map[Set[String], Set[String]], etc.
One simple example, and one of my failed approach:
abstract class Parent {
def mainfunc(): String = {
//logic
func(Map[Any, Any])
}
def func(Map[Any, Any]): String
}
class Child1 {
override def func(Map[String, String]): String = {
//logic
}
}
class Child3 {
override def func(Map[String, Set[String]]): String = {
//logic
}
}
class Child3 {
override def func(Map[Set[String], Set[String]]): String = {
//logic
}
}
I tried Any
but I got this error: Any does not match String: class String in package lang is a subclass of class Any in package scala
The function func
is necessary to be in the parent class, because some functions in the parent class require it.
Could there be something wrong with my project design?
Upvotes: 0
Views: 662
Reputation: 27356
This is not possible because an override
method must accept all possible values accepted by the method it is overriding. Otherwise you could call the abstract method with types that the overridden method doesn't support, breaking type safety. Since func
in Parent
takes Map[Any, Any]
the overridden func
in the children must also take Map[Any, Any]
.
It might be possible to do something with type
members in the abstract class
but the details depend on how these classes are going to be used.
Upvotes: 1