14

Is there a way to extends another class from an Anonymous class in Scala? I means something like

abstract class Salutation {
  def saybye(): String = "Bye"
}

class anotherClass() {
  def dummyFunction() = {

    val hello = new {
      def sayhello(): String = "hello" 
    } extends Salutation

    val hi  = hello.sayhello //hi value is "Hello"
    val bye = hello.saybye   //bye value is "bye"
  }
}
Electric Coffee
  • 11,733
  • 9
  • 70
  • 131
frank
  • 1,761
  • 2
  • 16
  • 20

2 Answers2

15

Yep, and it looks pretty much the same as it does in Java:

abstract class Salutation {
  def saybye: String = "Bye"
}

val hello = new Salutation {
  def sayhello: String = "hello" 
}

val hi = hello.sayhello
val bye = hello.saybye

If Salutation is an abstract class or trait with a sayhello method with the same signature, you'll have provided an implementation; otherwise you'll have created an instance of an anonymous structural type:

hello: Salutation{def sayhello: String}

Note that calls to the sayhello method involve reflection (because of the way structural types are implemented in Scala), so if you're using this method heavily you should probably define a new trait or class.

Travis Brown
  • 138,631
  • 12
  • 375
  • 680
  • I didn't specified it at first, but yes Salutation is abstract... Salutation don't have sayHello, but it have some other function that I need and want to use. Is there another way without creating a "real" class? – frank Jul 09 '14 at 15:39
  • Yes, the code I give above will work, and you'll get an instance of `Salutation{def sayhello: String}` that you can call both methods on. – Travis Brown Jul 09 '14 at 15:40
  • Hmmm I am supposed to use it like this : " val hello: Salutation{def sayhello: String} " If so, how I define what sayhello does and how I instantiate it? – frank Jul 09 '14 at 15:57
  • 1
    The type of `hello` (including the `sayhello` method signature) will be inferred—you don't need to write it. The code above is all you need to instantiate the class. – Travis Brown Jul 09 '14 at 16:01
  • So I should have something like : " val hello : Salutation{def sayhello: String} = new Salutation { def sayhello: String = "hello" } " If not, I don't understand what I need to write. If so, I get this error : "Cannot resolve constructor" – frank Jul 09 '14 at 16:08
2

You need to do:

val hello = new Salutation {
    def sayhello(): String = "hello" 
}
wingedsubmariner
  • 13,350
  • 1
  • 27
  • 52
  • 2
    You beat me by a minute, but I don't think this kind of context-less, code-only answer is generally a good thing on Stack Overflow—especially in a case like this where there's a lot of potentially confusing nuance. – Travis Brown Jul 09 '14 at 15:32
  • I'm sorry, my question wasn't complete... I changed it, should be clearer now :) – frank Jul 09 '14 at 15:36