Etam
Etam

Reputation: 4673

Scala class substitution

There is a Java library with classes:

class DefaultFieldFactory {
  ...
  public static String createCaptionByPropertyId(Object propertyId) { ... }
  ...
}

class FieldFactory extends DefaultFieldFactory {
  ...
  // Lot of methods that use DefaultFieldFactory.createCaptionByPropertyId
  ...
}

I am using the FieldFactory class in a Scala project and I need to alter createCaptionByPropertyId method.

How can I do it without AOP and rewriting the FieldFactory class?

Is it possible to substitute DefaultFieldFactory class implementation in package? It is relatively simple and short.

Thanks in advance, Etam.

Upvotes: 1

Views: 226

Answers (2)

Mark
Mark

Reputation: 477

I think there is a hacky way to do it... But if you have the source code for the original java class I would strongly recommend you change it.

If not you can create a new implementation of DefaultFieldFactory as an object in your class that hides the original implementation within your class. Then the implementation of the DefaultFieldFactory object can call through to the original java implimentations.

// in package x.y.a
class DefaultFieldFactory {
  ...
  public static String createCaptionByPropertyId(Object propertyId) { ... }
  ...
}

// in package x.y.b
class FieldFactory extends DefaultFieldFactory {

  object DefaultFieldFactory{


    def createCaptionByPropertyId(propertyId: AnyRef): String { 
      //import the original implimentation
      import x.y.b.DefaultFieldFactory._
      ... 
    }
  }


  // Lot of methods that use DefaultFieldFactory.createCaptionByPropertyId
  ...
}

Like I say... not nice!

Upvotes: 1

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297265

A static class would go into an object in Scala, which would not inherit the static methods of DefaultFieldFactory -- which, in fact, reflects well the fact that you can't override statics.

This is one reason why statics are frowned upon.

Upvotes: 2

Related Questions