Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala How to use extends with an anonymous class

Tags:

scala

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"
  }
}
like image 392
frank Avatar asked Jul 09 '14 15:07

frank


People also ask

Can Anonymous classes extend?

The syntax of anonymous classes does not allow us to make them implement multiple interfaces. During construction, there might exist exactly one instance of an anonymous class. Therefore, they can never be abstract. Since they have no name, we can't extend them.

What is anonymous class in Scala?

In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. Moreover an anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.

How do I extend a class in Scala?

To extend a class in Scala we use extends keyword. there are two restrictions to extend a class in Scala : To override method in scala override keyword is required. Only the primary constructor can pass parameters to the base constructor.

Why do we use anonymous class in Java?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.


1 Answers

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.

like image 193
Travis Brown Avatar answered Sep 28 '22 11:09

Travis Brown