1

We can supply parameter to a class extending trait with the same name as an abstract method like

trait Trr{
   def m: String
}

case class Trrrr(m: String) extends Trr  //fine

This example compiles fine. But I tried to do something like that with case objects and failed:

trait Command{
  def name: String
}

case object Unload("unld") extends Command //compile error

Is there a way to write this concisely while leaving Command a trait, not an abstract class with parameter? I mean not like that:

case object Unload extends Command {
  override def name: String = "unld"
}

or

abstract class Command(name: String)

case object Unload extends Command("unld")
1
  • 2
    There isn't another way that is more concise. Commented Jun 22, 2017 at 12:51

2 Answers 2

3
case object Unload extends Command { val name = "unld" }

Object don't have arguments, things won't get any shorted than the above...

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

Comments

1

You can instantiate the trait directly like so:

val newTrr = new Trr { val m = "example" }

At this point you can use the newTrr value just like any class instance...

println(newTrr.m)

which will print out: "example".

Comments

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.