Reputation: 19
I am trying to build a Scala application in which the user can load in classes that implement an interface defined by a trait, which the application will then use.
For example, my Operator trait
trait Operator {
def operate(a: Int, b: Int): Int
}
is implemented by a user-defined class to be loaded in at run time, Add.
class Add {
def operate(a: Int, b: Int): Int = a + b
}
How can the application check that this Add class implements the Operator trait it knows about? I would like to be able to call operate
on an instance of the loaded class.
I have tried simple pattern matching like this
case op: Class[Operator] => op.newInstance()
but this appears to check implementation based on trait name rather than member signatures.
Upvotes: 0
Views: 557
Reputation: 13985
First of all, lets clear the terminology, your class
Add
simply does not implement
the Operator
trait which you defined. You should not and can not use clearly defined terms to mean something different compared to their actual meaning.
Now, what you are looking for are structural types
and not traits
.
Lets define a strucural type
with name IsOperator
,
type IsOperator = {
def operate(a: Int, b: Int): Int
}
And lets define something logic which uses this,
def perform(a: Int, b: Int, o: IsOperator): Int = o.operate(a, b)
Now, any object
or instance of any class
which confirms to the structural type
IsOperate
(has a method named operate
with type (Int, Int) => Int
) can be used with perform
.
object Add {
def operate(a: Int, b: Int): Int = a + b
}
val sum = perform(1, 2, Add)
// sum: Int = 3
Upvotes: 3