没有参数的Scala构造函数 [英] Scala constructor without parameters

查看:55
本文介绍了没有参数的Scala构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能在这里遇到了一个愚蠢的问题...我似乎无法弄清楚如何在 Scala 中创建没有参数的构造函数.我知道我可以在类主体中编写整个内容(特别是因为它是我唯一需要的构造函数),但感觉不太对.

I may be having a silly problem here... I can't seem to figure out how to make a constructor without parameters in Scala. I know I can just write the whole thing in the class body (especially because it's the only constructor I need), but it doesn't quite feel right.

我有什么:

    class Foo {
        //some init code

        //...
    }

我想要什么(但不起作用,因为它希望我先调用另一个构造函数):

What I'd like (but doesn't work as it wants me to call another constructor first):

    class Foo {
        // The only constructor
        def this() = { 
            //some init code
        }

        //...
    }

推荐答案

Scala 中的所有类都有一个主构造函数和一些可选的辅助构造函数(必须服从主构造函数或另一个辅助构造函数).

All classes in Scala have a primary constructor and optionally some auxiliary constructors (which must defer to the primary constructor or another auxiliary constructor).

您的情况的问题是,在这两种情况下,您都将主构造函数定义为不带参数 - 然后在第二种情况下,您尝试定义具有相同签名的辅助构造函数.这不起作用,原因与以下内容无法编译的原因相同:

The issue in your case is that in both cases you've defined the primary constructor as taking no arguments - and then in the second case you try to define an auxiliary constructor with the same signature. This doesn't work, for the same reason that the following wouldn't compile:

// Primary constructor takes a String
class Foo(s: String) {
    // Auxiliary constructor also takes a String?? (compile error)
    def this(a: String) {
        this(a)
    }
}

这与构造函数是无参数的事实没有任何关系;例如以下编译:

This isn't anything to do with the fact that the constructor is no-args; the following compiles for example:

class Foo(s: String) {
    // alternative no-arg constructor (with different signature from primary)
    def this() {
        this("Default value from auxiliary constructor")
    }
}

特别是,在您的第二个示例中,您的注释唯一的构造函数"错误.辅助构造函数总是次于主构造函数,并且永远不可能是唯一的构造函数.

In particular, in your second example, your comment "the only constructor" is wrong. Auxiliary constructors are always secondary to the primary constructor, and cannot ever be the only constructor.

FWIW,第一个示例是唯一向您开放的选项,但对我来说看起来不错.如果您刚刚开始使用 Scala,我相信它很快就会开始感觉良好 - 当有更多惯用的替代方案时,避开 Java 式的做事方式很重要.

FWIW, the first example is the only option open to you, but it looks fine to me. If you've just started using Scala I'm sure it will start to feel right soon enough - and it's important to eschew Java-esque ways of doing things when there are more idiomatic alternatives.

这篇关于没有参数的Scala构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆