@BeanProperty and 'this' constructors in a class


#1

I have been looking at some Scala code written by someone else a while ago. Some of that codebase needs cleanup. For example, I don’t see any case classes in this codebase.

So, here is an shortened representation of a class from that codebase. Its looks like the code below:

class X (@BeanProperty val dc: DoubleContainer, private val _ps: List[DoubleContainer],
@BeanProperty val aS: Double, @BeanProperty val bS: Double) {

private val _d1: Container1[DoubleContainer] = (p1: DoubleContainer, p2: DoubleContainer) =>
functionReturningDouble(p1, p2) * aS

private val _d2: Container1[DoubleContainer] = (p1: DoubleContainer, p2: DoubleContainer) =>
functionReturningDouble(p1, p2) * bS

def this(dc: DoubleContainer, dcs: List[DoubleContainer], b: Double) = this(dc, dcs, 1, b)

def this(i: Container2, a: Double, b: Double) =
this(i.dc, i._ps, a, b)

}
The DoubleContainer and Container2 are classes that don’t need to be represented here.
Class X resembles a Javabean somewhat and doesn’t look very nice. I don’t see any reason why those @BeanProperty annotations should be present. I am not sure what it is doing here.,

Can this be rewritten as a case class without all those ‘this’ constructors?
Perhaps I need to create apply() methods?

Thanks,.


#2

@BeanProperty provides java-style getters and setters. If the calling code doesn’t need or expect those, you don’t need it. To a caller, this class will look like a perfectly normal java class. That was probably the original intent. You can remove them if they’re no longer used.


#3

I would like to transform the java style class (mutable fields ??) into a case class. What is your suggestion?


#4

It’s a bit hard to say with no context: _ps and dc are unused in the example. A private val is a yellow flag here, and as its unused, I cant see whether there is a logical refactoring.


#5

Thank you for pointing that out. I will fix my code first. That should make it clearer, I think


#6

This is the updated code: ‘dc’ in the previous code should have been dp, so it is renamed. I have used dp down in the rect function, and _ps in the plSize function.
To add more context, there is a Shape and then instances of it, like rectangle.

class X ( @BeanProperty val dp: DoubleContainer,
val _ps: List[DoubleContainer],
@BeanProperty val dS: Double,
@BeanProperty val fS: Double ) {

val _d: Container1[DoubleContainer] = (g1: DoubleContainer, g2: DoubleContainer) => functionReturningDouble(g1, g2) * dS

 val _f: Container1[DoubleContainer] = (g1: DoubleContainer, g2: DoubleContainer) => functionReturningDouble(g1, g2) * fS

def this(dp: DoubleContainer, pls: List[DoubleContainer], f: Double) = this(dp, pls, 1, f)

def this(rect: Rectangle, d: Double, f: Double) = this(rect.dp, rect._ps, d, f)

def plSize = _ps.size  //usage of _ps
def rect = new Rectangle(dp, 10, dS,fS)   //usage of dp (this was 'dc' before)

}