English 中文(简体)
在Schala通过受扶养物品给父母的建筑商
原标题:Passing dependent objects to a parent constructor in Scala

附录 我的等级为:

class A()
class B(a:A)
class C(b:B)

class BaseClass(b:B, c:C)

现在,我想执行一个分级的基地地图集,这是A例,并修建了B和C号卫星,它转往超级建筑商。

如果我可以任意表达,我就这样做了:

b = new B(a)
c = new C(b)
super(b, c)

由于向上级建筑商提出的第二个论点取决于第一种论点的价值,但我看不出这样做的任何方法,而没有使用工厂功能,也不使用粗略的黑板,例如:

class IntermediateSubclass(b:B) extends BaseClass(b, new C(b))
class RealSubclass(a:A) extends IntermediateSubclass(new B(a))

是否有这样做的清洁方法?

最佳回答

或许,处理这种局面的最佳途径是,在你想要书写的基地目录的附庸上写一个工厂方法。

class A()
class B(a:A)
class C(b:B)

class BaseClass(b:B, c:C)

class SBC private (a: A, b: B, c: C)
extends BaseClass(b, c)

object SBC
{
    def
    apply(a: A): SBC = {
        val b = new B(a)
        val c = new C(b)
        new SBC(a, b, c)
    }
}

如果你不熟悉这些星号,你可以将任何构造参数输入田地,而不会影响任何东西(通过预设<>val)。

class A()
class B(val a: A)
class C(val b: B)

class BaseClass(val b: B, val c: C)

class SBC private (val a: A, b: B, c: C)
extends BaseClass(b, c)

object SBC
{
    def
    apply(a: A): SBC = {
        val b = new B(a)
        val c = new C(b)
        new SBC(a, b, c)
    }
}

现在可以以这种表述方式产生新的<代码>SBC:SBC(aValue)(不论是否使用<代码>val)。

scala> val a1 = new A
a1: A = A@14a8f44

scala> val sbc1 = SBC(a1)
sbc1: SBC = SBC@7d8bb

scala> sbc1.a
res0: A = A@14a8f44

scala> sbc1.b
res1: B = B@c7272

scala> sbc1.c
res2: C = C@178743b
问题回答

暂无回答




相关问题
UserControl constructor with parameters in C#

Call me crazy, but I m the type of guy that likes constructors with parameters (if needed), as opposed to a constructor with no parameters followed by setting properties. My thought process: if the ...

Strange "type class::method() : stuff " syntax C++

While reading some stuff on the pImpl idiom I found something like this: MyClass::MyClass() : pimpl_( new MyClassImp() ) First: What does it mean? Second: What is the syntax? Sorry for being such ...

Anonymous class question

I ve a little doubt over this line: An anonymous class cannot define a constructor then, why we can also define an Anonymous class with the following syntax: new class-name ( [ argument-list ] ) {...

Why copy constructor is not called in this case?

Here is the little code snippet: class A { public: A(int value) : value_(value) { cout <<"Regular constructor" <<endl; } A(const A& other) : value_(other....

Invoking an instance method without invoking constructor

Let s say I have the following class which I am not allowed to change: public class C { public C() { CreateSideEffects(); } public void M() { DoSomethingUseful(); } } and I have to call M ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

热门标签