0
class A 

class B extends A

object B {
  def createSidekick = new B
}

class C extends A

object C {
  def createSidekick = new C
}

object foo {
  def bar[T <: C] = {
    // T.createSidekick
  }
}

In foo.bar, I would like to call methods from the given object. However, Scala does not allow to extend objects, so there is no obvious way of accomplishing this. What is the best way to accomplish this sort of behaviour?

1 Answer 1

1

Something like this?

class A

class B extends A

trait Sidekicker[T <: A] {
  def createSidekick: T
}

object B extends Sidekicker[B] {
  def createSidekick = new B
}

class C extends A

object C extends Sidekicker[C] {
  def createSidekick = new C
}

object foo {
  def bar(s: Sidekicker[_]) = s.createSidekick

  val b = bar(B)
  val c = bar(C)
}
Sign up to request clarification or add additional context in comments.

6 Comments

I was hoping there might be some elegant solution where I just use the Type parameter
Do you mean bar[B] instead of bar(B)? Well, that's just a matter of personal taste whether you like more rounded shapes or sharp ones.
@user1225310: You could use type classes like this: link to pastebin.com. Note that you could define implicit val for Sidekicker[T] not only in companion object.
@RadoBuransky: you could add typeclasses implementation as alternative option to your answer.
@senia: Interesting, thanks. When would you recommend "mine" and where "your" approach?
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.