scala中重载构造函数中的逻辑

San*_*tta 1 java scala

我试图在重载的构造函数中添加一些处理逻辑,但似乎无法让它工作.

这是我想要做的简化示例:

class FooBar(val x: String, val y: String) {

    this(z: String) = {
        // DO SOME ARBITRARY CODE
        val x = // SOME ARBITRARY PROCESSING USING z
        val y = // SOME ARBITRARY PROCESSING USING z
        this(x, y)
    }
 }
Run Code Online (Sandbox Code Playgroud)

但是,我收到编译错误:

: 'this' expected but 'val' found
Run Code Online (Sandbox Code Playgroud)

这是Java中一个非常简单的任务,我只需x, y从2个独立的构造函数中设置实例变量.

这是我的Java等同于我想要完成的事情:

class FooBar {

    public String x;
    public String y;

    public FooBar(String x, String y) {
        this.x = x;
        this.y = y;
    }

    public FooBar(String z) {
        // DO SOME ARBITRARY CODE
        this.x = // SOME ARBITRARY PROCESSING USING z
        this.y = // SOME ARBITRARY PROCESSING USING z
    }
}
Run Code Online (Sandbox Code Playgroud)

===================编辑==================

我决定使用@ om-nom-nom的方法使用伴侣对象.然而,正如@ om-nom-nom指出的那样,没有办法绕过丢失的new调用.因此,为了使我的构造函数一致,我重载apply了伴随对象中的方法:

class FooBar(val x: String, val y: String)
object FooBar {
    def apply(x: String, y: String) = new FooBar(x, y)

    def apply(z: String) = {
        // DO SOME ARBITRARY CODE
        val x = // SOME ARBITRARY PROCESSING USING z
        val y = // SOME ARBITRARY PROCESSING USING z
        new FooBar(x, y)
    }
}

FooBar(someX, someY)
FooBar(someZ)
Run Code Online (Sandbox Code Playgroud)

om-*_*nom 5

通常通过伴随对象完成(尽管可以将一些表达式作为参数嵌入到第一行调用中,如@TheTerribleSwiftTomato所示):

class FooBar(val x: String, val y: String)
object FooBar {
    def apply(z: String) = {
        // DO SOME ARBITRARY CODE
        val x = // SOME ARBITRARY PROCESSING USING z
        val y = // SOME ARBITRARY PROCESSING USING z
        new FooBar(x, y)
    }
}

FooBar(someZ)
Run Code Online (Sandbox Code Playgroud)

请注意,new调用时没有关键字,也无法克服这个问题.