0

Suppose I have a trait A and a class A1 that extends A:

trait A
class A1 extends A

and A1 has some unique property:

class A1 extends A { val hello = "hello" }

and I have a method that I want to handle all subclasses of trait A:

def handle:A = new A1

but, if I try to access unique properties defined in A1, understandably, it doesn't work:

scala> handle.hello
<console>:11: error: value hello is not a member of A
              handle.hello
                     ^

Once I'm done handling instances of subclasses of A as As, how do I once again access them with all their unique properties? How does this mechanism work?

Jens Bergvall
  • 1,617
  • 2
  • 24
  • 54
Dominykas Mostauskis
  • 7,797
  • 3
  • 48
  • 67

2 Answers2

3

There are various mechanisms of varying complexity available to deal with this, but possibly the easiest and most common would be pattern matching:

val a = get
...do stuff with a as an `A`...
a match {
  case a1: A1 => a1.hello
  ...other case clauses for other subtypes of A, if required...
  case _ => println("Not a known sub-type of A")
}

Another mechanism involves ClassTags and/or TypeTags (or Manifests, pre Scala 2.10 or so), with which I am less familiar.

Shadowlands
  • 14,994
  • 4
  • 45
  • 43
  • I'll look around for articles on `ClassTag`s and `TypeTag`s. Any suggestions maybe? – Dominykas Mostauskis Oct 16 '13 at 12:05
  • Try [here](http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html) and [here](http://stackoverflow.com/questions/12218641/scala-2-10-what-is-a-typetag-and-how-do-i-use-it). – Shadowlands Oct 16 '13 at 12:20
0

One of the possible mechanisms is to define additional interfaces as traits. For example:

scala> class A
defined class A

scala> trait A1 { val hello = "hello" }
defined trait A1

scala> def handle:A with A1 = new A() with A1
handle: A with A1

scala> handle.hello
res0: String = hello
Ashalynd
  • 12,363
  • 2
  • 34
  • 37
  • How does this help in a generic method handling subclasses of A? It isn't known at compile time if the instance of `A` is also `A with A1`, to find that out you need pattern matching or casting. – danielkza Oct 16 '13 at 11:42