Scala抽象类型表示子类的类型 [英] Scala abstract type representing type of subclass

查看:46
本文介绍了Scala抽象类型表示子类的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来定义返回类型 T 的方法,其中 T = 子类的类型.

I'm looking for a way to define a method that returns a type T where T = the type of the subclass.

我知道我可以使用抽象类型来做到这一点,但不喜欢必须为每个子类重新定义 T 的开销.

I know I could possibly do this using abstract types, but dislike the overhead of having to redefine T for each subclass.

一些示例代码:

object Helper {
  def help[A <: MyClass](cls: A): Option[A] = { cls.foo() map { _.asInstanceOf[A] } }
}

class MyClass {
  type T <: MyClass
  def foo(): Option[T] = Some(this.asInstanceOf[T])
}

class ChildClass extends MyClass {
   type T = ChildClass
}

可能是新的语言功能使这变得更容易了?或者我可以以某种方式使用 this.type 吗?能够以这种方式定义一个可以调用 foo 的辅助类对我来说很重要.

Possibly a new language feature has made this easier? Or can I use this.type in some way? It's important to me that I be able to define a helper class that can call into foo in this way.

推荐答案

如果你总是返回this,那么你确实可以将this.type作为返回类型.或者你已经试过了?

If you are always returning this, then you can indeed have as return type this.type. Or have you tried it already?

this.type 特别有用,例如当您想将调用链接到同一个对象,或提供静态保证您将返回同一个对象(而不是副本)时.例如,Scala 中的 Buffer 有附加操作 :+,它返回一个 Buffer[A],并且 +=,返回 this.type.前者复制可变序列;后者保证您更新原始对象.

this.type is especially useful e.g. when you want to chain calls to the same object, or provide a static guarantee that you will be returning the same object (and not a copy). For instance, Buffers in Scala have the append operation :+, which returns a Buffer[A], and +=, which returns this.type. The former duplicates the mutable sequence; the latter guarantees that you update the original object.

这篇关于Scala抽象类型表示子类的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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