Scala 如何在匿名类中使用扩展 [英] Scala How to use extends with an anonymous class

查看:37
本文介绍了Scala 如何在匿名类中使用扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从 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"
  }
}

推荐答案

是的,它看起来与 Java 中的几乎一样:

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

如果 Salutation 是一个抽象类或具有相同签名的 sayhello 方法的特征,您将提供一个实现;否则,您将创建一个匿名结构类型的实例:

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}

请注意,对 sayhello 方法的调用涉及反射(因为结构类型在 Scala 中实现的方式),因此如果您大量使用此方法,您可能应该定义一个新的特征或类.

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.

这篇关于Scala 如何在匿名类中使用扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆