【问题标题】:Scala Constructor DeprecationScala 构造函数弃用
【发布时间】:2013-04-09 08:31:30
【问题描述】:

我在 Scala 中有一个类,目前以标准方式构建:

class Test( int : Int )
{
    override def toString() = "Test: %d".format( int ) 
}

但是,我想通过伴随对象转到间接构造。由于我正在修改的库被其他人使用,我不想立即将构造函数设为私有。相反,我想弃用它,然后在人们有机会改变他们的使用方式后返回并将其设为私有。所以我像这样修改了我的代码:

object Test
{
    def apply( int : Int ) = new Test( int )
}

@deprecated( "Don't construct directly - use companion constructor", "09/04/13" )
class Test( int : Int )
{
    override def toString() = "Test: %d".format( int ) 
}

但是,这会弃用整个类。

scala> Test( 4 )
<console>:10: warning: class Test in package foo is deprecated: Don't construct directly - use companion constructor
       val res0 =
           ^
res0: com.foo.Test = Test: 4

有谁知道 Scala 是否支持弃用构造函数,如果支持,它是如何实现的?

【问题讨论】:

    标签: scala constructor annotations deprecated


    【解决方案1】:

    This thread 似乎描述了解决方案:

    object Test
    {
        def apply( int : Int ) = new Test( int )
    }
    
    
    class Test @deprecated( "Don't construct directly - use companion constructor", "09/04/13" ) ( int : Int )
    {
        override def toString() = "Test: %d".format( int ) 
    }
    

    但现在不能尝试。

    【讨论】:

    • (已编辑)这确实有效,但它不是绝对理想的,因为在导入此类时会收到弃用警告,因为伴随对象调用了弃用的构造函数 - 有什么想法可以解决这个问题吗?
    • 你确定吗?编译 Test 时应该会收到警告,但在导入时不会。
    【解决方案2】:

    就我的特殊情况而言,由于伴随对象使用已弃用的构造函数,弃用构造函数会导致编译时出现弃用警告,一位同事建议我使用虚拟参数提供第二个构造函数,并弃用没有的构造函数:

    object Test
    {
        def apply( int : Int ) = new Test( int, false )
    }
    
    
    class Test ( val int : Int, dummy : Boolean )
    {
        @deprecated( "Don't construct directly - use companion constructor", "09/04/13" )
        def this( int : Int ) = this( int, false )
    
        override def toString() = "Test: %d".format( int ) 
    }
    

    这行得通,因为如果用户调用已弃用的构造函数,只会有弃用警告,但显然这很不愉快 - 有没有人有更好的解决方案?

    【讨论】:

    • 卓越的解决方案是 Jens Schauder 已经提供的解决方案
    • 但在这种特定情况下,这并不是真正的解决方案 - 要求用户用其他警告弃用的东西替换警告弃用的东西并不理想......?
    • 我以为您已经承认它不会警告客户端代码的弃用(您只会在编译Test时收到警告)?
    • UnitDummyImplicit 可能更适合用于 dummy 参数,因为它们不包含任何信息(Boolean 包含一点)
    猜你喜欢
    • 1970-01-01
    • 2017-05-02
    • 2013-10-28
    • 2021-09-10
    • 2017-12-04
    • 2013-09-08
    • 2011-02-11
    • 2013-06-14
    • 2012-01-09
    相关资源
    最近更新 更多