मेरे पास एक डिज़ाइन पैटर्न है जहां ऑब्जेक्ट जेनरेटर (मॉर्सल जेनरेटर और उसके बच्चे) हैं, जिनमें से कोई भी उदाहरण हमेशा एक ही सटीक प्रकार की ऑब्जेक्ट उत्पन्न करता है (मोर्सल्स और उसके बच्चे), लेकिन टाइप चेकर मुझे इन उत्पन्न वस्तुओं में से दो या अधिक पर कोई भी संचालन करने नहीं देगा, मानते हैं कि वे अलग हो सकते हैं।स्कैला प्रकार अनुमान इस बात को ध्यान में रखता है कि ये प्रकार समान हैं, जो भी
मैं इस प्रकार के प्रकार चेकर को कैसे प्राप्त करूं?
trait Morsel
{
type M <: Morsel
def calories : Float
def + (v : M) : M
}
trait MorselGenerator
{
type Mg <: Morsel
def generateMorsel : Mg
}
class HotDog(c : Float, l : Float, w : Float) extends Morsel
{
type M = HotDog
val calories : Float = c
val length : Float = l
val width : Float = w
def + (v : HotDog) : HotDog = new HotDog(v.calories + calories, v.length + length, v.width + width)
}
class HotDogGenerator extends MorselGenerator
{
type Mg = HotDog
def generateMorsel : HotDog = new HotDog(500.0f, 3.14159f, 445.1f)
}
object Factory
{
def main (args : Array[String])
{
val hdGen = new HotDogGenerator()
println(eatTwo(hdGen))
}
def eatTwo (mGen : MorselGenerator)
{
val v0 : mGen.Mg = mGen.generateMorsel
val v1 : mGen.Mg = mGen.generateMorsel
v0 + v1 /// ERROR HERE
}
}
संकलक निम्नलिखित संकलन त्रुटि
Generator.scala:43: error: type mismatch;
found : v1.type (with underlying type mGen.Mg)
required: v0.M
v0 + v1 /// ERROR HERE
^one error found
उत्पन्न
अद्यतन
यहाँ सी ++ कोड कम या ज्यादा मैं क्या कर रहा हूँ के बराबर है कि है। ध्यान दें कि खाने दो कार्य पूरी तरह से polymorphic है और विशिष्ट व्युत्पन्न प्रकार के मोर्सेल या मोर्सेल जेनरेटर का कोई संदर्भ नहीं देता है।
#include <stdlib.h>
#include <stdio.h>
template <class M> class Morsel
{
public:
Morsel(float c) : calories(c) {}
float calories;
virtual M operator + (const M& rhs) const = 0;
};
template <class M> class MorselGenerator
{
public:
virtual M * generateMorsel() const = 0;
};
class HotDog : public Morsel<HotDog>
{
public:
HotDog(float c, float l, float w) : Morsel<HotDog>(c), length(l), width(w) {}
float length, width;
HotDog operator + (const HotDog& rhs) const
{ return HotDog(calories+rhs.calories, length+rhs.length, width+rhs.width); }
};
class HotDogGenerator : public MorselGenerator<HotDog>
{
HotDog * generateMorsel() const { return new HotDog(500.0f, 3.14159f, 445.1f); }
};
///////////////////////////////////////////////
template <class MorselType> float eatTwo (const MorselGenerator<MorselType>& mGen)
{
MorselType * m0 = mGen.generateMorsel();
MorselType * m1 = mGen.generateMorsel();
float sum = ((*m0) + (*m1)).calories;
delete m0; delete m1;
return sum;
}
int main()
{
MorselGenerator<HotDog> * morselStream = new HotDogGenerator();
printf("Calories Ingested: %.2f\n", eatTwo(*morselStream));
delete morselStream;
}
शायद यह मदद करेगा: http://stackoverflow.com/questions/9198562/scala-self-type-and-this-type-in-collections-issue – tuxSlayer