Scala How to use extends with an anonymous class

后端 未结 2 1944
花落未央
花落未央 2021-01-02 04:57

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\"         


        
2条回答
  •  有刺的猬
    2021-01-02 05:13

    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.

提交回复
热议问题