gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:37:00 24 4
gpt4 key购买 nike

我试图在重载的构造函数中添加一些处理逻辑,但似乎无法使其正常工作。

这是我想做的一个简化示例:

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)
}
}

但是,我遇到了一个编译错误:

: 'this' expected but 'val' found

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

这是我想要完成的 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
}
}

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

我决定采用@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)

最佳答案

通常通过伴生对象完成(尽管有可能 embed some expression as argument to the first-line-call, as @TheTerribleSwiftTomato shown ):

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)

请注意,调用时没有 new 关键字,因此无法克服这一点。

关于java - scala 重载构造函数中的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19126797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com