2

I have the following setup:

trait A
{
  def doSomething(): Unit;
}

object B extends A
{
 override def doSomething(): Unit = 
 {
   // Implementation
 }
}

class B(creator: String) extends A
{
 override def doSomething(): Unit =
 {
   B.doSomething() // Now this is just completely unnecessary, but the compiler of course insists upon implementing the method
 }
}

Now you may wonder why I even do this, why I let the class extend the trait as well.

The problem is, that somewhere in the Program there is a Collection of A. So somewhere:

private val aList: ListBuffer[A] = new ListBuffer[A]

and in there, I also have to put Bs (among other derivates, namely C and D)

So I can't just let the B-class not extend it.

As the implementation is the same for all instances, I want to use an Object.

But there is also a reason I really need this Object. Because there is a class:

abstract class Worker
{
 def getAType(): A

 def do(): Unit =
 {
   getAType().doSomething()
 }
}

class WorkerA
{
  def getAType(): A =
  {
    return B
  }
}

Here the singleton/object of B gets returned. This is needed for the implementation of do() in the Worker.

To summarize:

The object B is needed because of the generic implementation in do() (Worker-Class) and also because doSomething() never changes.

The class B is needed because in the collection of the BaseType A there are different instances of B with different authors.

As both the object and the class have to implement the trait for above reasons I'm in kind of a dilemma here. I couldn't find a satisfying solution that looks neater.

So, my question is (It turns out as a non-native-speaker I should've clarified this more)

Is there any way to let a class extend a trait (or class) and say that any abstract-method implementation should be looked up in the object instead of the class, so that I must only implement "doSomething()" (from the trait) once (in the object)? As I said, the trait fulfills two different tasks here. One being a BaseType so that the collection can get instances of the class. The other being a contract to ensure the doSomething()-method is there in every object.

So the Object B needs to extend the trait, because a trait is like a Java interface and every (!) Object B (or C, or D) needs to have that method. (So the only option I see -> define an interface/trait and make sure the method is there)

edit: In case anyone wonders. How I really solved the problem: I implemented two traits.

Now for one class (where I need it) I extend both and for the other I only extend one. So I actually never have to implement any method that is not absolutely necessary :)

5
  • A slightly more concrete example might help, you code is so general (A, B, doSomething, ...), it is difficult to help you. Commented Jul 15, 2015 at 21:24
  • What is your question? I read your request. Looks nice to have a trait that is extended by both an object and a class. You never ask anything. You mentioned that you couldn't find a solution that looks "neater". Would your concern maybe be better served at codereview.stackexchange.com ? Commented Jul 15, 2015 at 22:02
  • @Madoc: Hypothetical code is off-topic on Code Review. Commented Jul 15, 2015 at 22:03
  • @Jamal Thanks for the clarification. As long as nothing gets asked - and I don't think the question is implicit and obvious -, it also doesn't fit the Q&A format of SO. I hope that the author comes up with a clearer request. Commented Jul 15, 2015 at 22:06
  • @Madoc: I hope my edit clarifies this a bit! Commented Jul 16, 2015 at 8:55

3 Answers 3

1

As I wrote in the comment section, it's really unclear to me what you're asking. However, looking at your code examples, it seems to me that trait A isn't really required. You can use the types that already come with the Scala SDK:

object B extends (()=>Unit) {
  def apply() { /* implementation */ }
}

Or, as a variant:

object B {
  val aType:()=>Unit = {() => /* implementation */ }
}

In the first case, you can access the singleton instance with B, in the second case with B.aType. In the second case, no explicit declaration of the apply method is needed.

Pick what you like. The essential message is: You don't need a trait if you just define one simple method. That's what Scala functions are for.

The list type might look like this:

private val aList:ListBuffer[()=>Unit] = ???

(By the way: Why not declare it as Seq[()=>Unit]? Is it important to the caller that it is a ListBuffer and not some other kind of sequence?)

Your worker might then look like this:

abstract class Worker {
  def aType:()=>Unit // no need for the `get` prefix here, or the empty parameter list
  def do() {aType()}
}

Note that now the Worker type has become a class that offers a method that invokes a function. So, there is really no need to have a Worker class. You can just take the function (aType) directly and invoke it, just so.

If you always want to call the implementation in object B, well - just do that then. There is no need to wrap the call in instances of other types. Your example class B just forwards the call to the B object, which is really unnecessary. There is no need to even create an instance of B. It does have the private member variable creator, but since it's never used, it will never be accessed in any way.

So, I would recommend to completely remove the class B. All you need is the type ()=>Unit, which is exactly what you need: A function that takes no parameters and returns nothing.

If you get tired of writing ()=>Unit all the time, you can define a type alias, for example inside the package object. Here is my recommentation:

type SideEffect = ()=>Unit

Then you can use SideEffect as an alias for ()=>Unit.

That's all I can make of it. It looks to me that this is probably not what you were looking for. But maybe this will help you a little bit along the way. If you want to have a more concrete answer, it would be nice if you would clarify the question.

Sign up to request clarification or add additional context in comments.

7 Comments

But I need a trait as a contract to make sure every subclass has that method, right?
@Teolha ()=>Unit is already a trait which defines that contract. It's an alias for Function0[Unit]. No need to make up your own. What you call doSomething is called apply in Function0.
I see, thanks for the explanation. The problem I see with that, is that, the "... extends () => Unit" is nice, but a bit opaque for my colleagues. It's more intentional to extend an interface (or a trait in scalas case). If we have multiple classes that extend it, it's far easier to remember "A, well, each SubBlubb needs to extend that Blubb-trait" instead of... "SubBlubb extends () => Unit". At least that's how I see it. Technically it may well be a contract, but it's a contract one may overlook way easier. (I saw the alias-thingy ;))
@Teolha Ah, I think I see your point. In part, it's a question as to how far you and your team embrace Scala and go down the rabbit hole. Maybe you want to leave a bit of space for developers who are rather new in Scala, coming from a Java background. My personal opinion: If your team keeps using Scala, they will be learning and using constructs like this anyway, some point in the future. So why not right now?
Actually I'll stick with the trait(-class/file) for another reason... it implements more than one method now :)
|
1

object B doesn't really have much to do with class B aside from some special rules.

If you wish to reuse that doSomething method you should just reuse the implementation from the object:

class B {
  def doSomething() = B.doSomething()
}

If you want to specify object B as a specific instance of class B then you should do the following:

object B extends B("some particular creator") {
...
}

You also do not need override modifiers although they can be handy for compiler checks.

Comments

1

The notion of a companion object extending a trait is useful for defining behavior associated with the class itself (e.g. static methods) as opposed to instances of the class. In other words, it allows your static methods to implement interfaces. Here's an example:

import java.nio.ByteBuffer

// a trait to be implemented by the companion object of a class
// to convey the fixed size of any instance of that class
trait Sized { def size: Int }

// create a buffer based on the size information provided by the
// companion object
def createBuffer(sized: Sized): ByteBuffer = ByteBuffer.allocate(sized.size)

class MyClass(x: Long) {
  def writeTo(buffer: ByteBuffer) { buffer.putLong(x) }
}
object MyClass extends Sized {
  def size = java.lang.Long.SIZE / java.lang.Byte.SIZE
}

// create a buffer with correct sizing for MyClass whose companion
// object implements Sized. Note that we don't need an instance
// of MyClass to obtain sizing information.
val buf = createBuffer(MyClass)

// write an instance of MyClass to the buffer.
val c = new MyClass(42)
c.writeTo(buf)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.