How can I ensure that the arguments to trickyMethod are the same at compile time, but at the same time also have a common super type Fruit ?
In other words, tricky.trickyMethod(new Banana,new Apple) should not be compiled.
I'm sure there should be a simple solution, but I just spent 1 hour searching for an answer and still don't know :(
I tried implicit evidence with <: <but I couldn't get it to work.
class Fruit class Apple extends Fruit class Banana extends Fruit class TrickyClass[T<:Fruit]{ def trickyMethod(p1:T,p2:T)= println("I am tricky to solve!") } object TypeInferenceQuestion extends App{ val tricky=new TrickyClass[Fruit]() tricky.trickyMethod(new Apple,new Apple) //this should be OK tricky.trickyMethod(new Banana,new Banana) //this should be OK tricky.trickyMethod(new Banana,new Apple) //this should NOT compile }
EDIT:
Thanks for answers!
The following (more general) question:
This second example is a more general example of the first example.
class Fruit class Apple extends Fruit class Banana extends Fruit class TrickyClass[T]{ def trickyMethod[S<:T](p1:S,p2:S)= println("I am tricky to solve!") } object TypeInferenceQuestion extends App{ val tricky=new TrickyClass[Fruit]() tricky.trickyMethod(new Apple,new Apple) //this should be OK tricky.trickyMethod(new Banana,new Banana) //this should be OK tricky.trickyMethod(new Banana,new Apple) //this should NOT compile }
types scala compilation type-inference type-systems
jhegedus
source share