Weird inheritance

152 views
Skip to first unread message

Nils Kilden-Pedersen

unread,
Dec 1, 2013, 4:42:16 PM12/1/13
to scala-user

I just found the equivalent of this in my code base:

case class Foo(bar: Int) extends {
  override def toString = bar.toString
}

Not sure how extends ever made it in there (probably a refactor leftover), but it does bring up a few questions:

  1. Is this valid syntax (per the spec)?
  2. Is there any difference if extends is removed?

If valid, I assume Foo is extending an anonymous class, but classOf[Foo].getSuperclass just yields Object.

Benjamin Jackman

unread,
Dec 5, 2013, 11:26:27 PM12/5/13
to scala...@googlegroups.com

Som Snytt

unread,
Dec 6, 2013, 1:34:28 AM12/6/13
to Benjamin Jackman, scala-user
It's not an early definition, notice the `with`:

scala> new { override def toString = "oops" } with AnyRef
<console>:1: error: only concrete field definitions allowed in early object initialization section
       new { override def toString = "oops" } with AnyRef
                          ^


Where is the one-question FAQ when you really need it?

From the book:

trait Greeting {
  val name: String
  val msg = "How are you, "+name
}
class C extends {
  val name = "Bob"
} with Greeting {
  println(msg)
}


From the compiler:

  lazy val syntaxAnalyzer = new {
    val global: Global.this.type = Global.this
  } with SyntaxAnalyzer {
    val runsAfter = List[String]()
    val runsRightAfter = None
    override val initial = true
  }


The strange syntax is the optional extends:  ‘extends’ ClassTemplate | [[‘extends’] TemplateBody]

where AnyRef is understood.  So it's optional.

Why is it indeed so strange?

If only there were this usage of the underscore:

class Foo extends _ {
  // stats
}




On Thu, Dec 5, 2013 at 8:26 PM, Benjamin Jackman <benjamin...@gmail.com> wrote:

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Simon Ochsenreither

unread,
Dec 6, 2013, 8:12:31 AM12/6/13
to scala...@googlegroups.com, Benjamin Jackman

The strange syntax is the optional extends:  ‘extends’ ClassTemplate | [[‘extends’] TemplateBody]

where AnyRef is understood.  So it's optional.

Should we get rid of that?
Reply all
Reply to author
Forward
0 new messages