2

Is there a way in scala to use a method m in the implementation of the method overriding the same method m?

As an example here is what I tried (note that toUpperCase is not implemented):

abstract class Person {
 def greet: String
}

class EnglishMan extends Person {
  abstract override def greet: String = 
  {
    return "hello"
  }
}

trait Angry extends Person {
abstract override def greet: String = 
{
  return toUpperCase(greet)
}
gen
  • 9,528
  • 14
  • 35
  • 64
  • 1
    It's not clear what you are looking to have happen. What String should Angry.greet uppercase? perhaps adding a class that extends Angry and showing what you expect the return of calling that class's greet method would be. As a side note, EnglishMan.greet() cannot be abstract, that's a syntax error. – Angelo Genovese May 12 '16 at 22:45
  • 1
    Code doesn't make sense as presented; if `Angry` extended `EnglishMan` (where, if you'd tried running your code, you'd find your "abstract" modifier is invalid), then you could use `super.greet.toUpperCase`. However I suspect you're looking for *self types*. See this question from recently: http://stackoverflow.com/q/36945333/770361 The same question has been asked before but I haven't seen a good solution. – Luigi Plinge May 12 '16 at 23:20

1 Answers1

0

Is this what you want?

scala> trait Person { def greet: String }
defined trait Person

scala> class EnglishMan extends Person { def greet = "hello" }
defined class EnglishMan

scala> class Angry extends EnglishMan { override def greet = super.greet.toUpperCase }
defined class Angry

scala>

scala> new EnglishMan().greet
res3: String = hello

scala> new Angry().greet
res4: String = HELLO

Note that trait Person is completely irrelevant to this exercise. You can invoke your superclass' methods (even when overriding that very method), but you can't have 2 methods on the same scope with the same name (that would be ambiguous for the compiler).

mlg
  • 1,447
  • 15
  • 19