如果我在Scala中定义多个重载的构造函数,我是否可以定义默认值? [英] Can't I define defaults if I define multiple overloaded constructors in Scala?

查看:743
本文介绍了如果我在Scala中定义多个重载的构造函数,我是否可以定义默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了多个构造函数,在它们中都有一些默认的参数值。看起来正确(我看不到任何歧义),但Scala(2.8)编译器抱怨:

I've defined multiple constructors, with some default argument values in all of them. Looks correct (I can't see any ambiguity), but Scala (2.8) compiler complains:


多重重载的构造函数的替代定义默认参数

multiple overloaded alternatives of constructor define default arguments

这是否意味着我不能为重载的构造函数定义默认值?

Does it mean that I can't define default values for overloaded constructors at all?

让我来说明情况(原始的,当然,但是说明):

Let me illustrate the situation (primitivized, of course, but illustrative):



class A(subject : Double, factor : Int = 1, doItRight : Boolean = true) {

  def this (subject : Int, factor : Int = 1, doItRight : Boolean = true) = {
    this(subject.toDouble , factor, doItRight)
  }

  def this (subject : String, factor : Int = 1, doItRight : Boolean = true) = {
    this(subject.toDouble , factor, doItRight)
  }

  def this () = {
    this(defaultSubject)
  }

}




推荐答案

直接从编译器的源代码:

Taken straight from the compiler's source code:

// only one overloaded alternative is allowed to define default arguments

一般来说,我不建议你混合重载和默认值。

In general, I wouldn't advise that you mix overloading and defaults. Even if there's no conflict it can make your code harder to read.

UPDATE

由于您添加了代码,现在很清楚,你不想/需要覆盖每个辅助构造函数的默认值。在你的特殊情况下,我甚至可能怀疑这些额外的构造函数的需要; Int => Double已经可以作为一个隐式转换,String => Double看起来像是你可能会改变类型系统:)

Since you added code, it's clear now that you don't want/need to override the default values for each secondary constructor. In your particular case, I might even question the need for those extra constructors at all; Int=>Double is already available for you as an implicit conversion and String=>Double looks like you might be perverting the type system :)

替代重载的构造函数,您可以只使用默认值定义主构造函数,然后重载随附对象的apply方法并将其用作工厂。这当然是完全可选的,但它很快通过使用案例类成为一种模式。

Also... As an alternative to overloaded constructors, you can define just the primary constructor with defaults, then overload the apply method of the companion object and use that as a factory. This is of course completely optional, but it's rapidly becoming established as a pattern through the use of case classes.

这篇关于如果我在Scala中定义多个重载的构造函数,我是否可以定义默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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