Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Constructor Deprecation

I have a class in Scala, which is currently constructed in the standard manner:

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

However, I'd like to move over to indirect construction via a companion object. As the library I'm modifying is used by others, I don't want to make the constructor private straight away. Instead, I'd like to deprecate it and then come back and make it private once people have had a chance to change their usage. So I modified my code like this:

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

However, this deprecates the whole class.

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

Does anyone know if Scala supports deprecation of constructors, and if so how it is done?

like image 358
paulmdavies Avatar asked Apr 09 '13 08:04

paulmdavies


2 Answers

This thread seems to describe the solution:

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

Can't try it right now though.

like image 51
Jens Schauder Avatar answered Nov 14 '22 10:11

Jens Schauder


In terms of my particular case, where deprecating the constructor causes a deprecation warning at compile time due to the companion object using the deprecated constructor, a colleague suggested I provide a second constructor using a dummy parameter, and deprecate the one without:

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

This works, in that there will only be deprecation warnings if the user is calling the deprecated constructor, but obviously it's unpleasant - does anyone have a superior solution?

like image 1
paulmdavies Avatar answered Nov 14 '22 10:11

paulmdavies