[英]Scala: Polymorphic daisy chaining
class Foo(protected[this] val s: Iterator[String]) {
def apply(it: Iterator[String]): Foo = new Foo(it ++ s)
}
class Bar(s: Iterator[String]) extends Foo(s) {
}
Question: How can I get Bar.apply()
to return a new Bar
instead of a new Foo
? 问题:如何让
Bar.apply()
返回一个new Bar
而不是一个new Foo
? I don't want to override. 我不想覆盖。
You can use F-bounded polymorphism to get an apply
that returns the proper type. 您可以使用F-bounded多态来获取返回正确类型的
apply
。 You also need to define a method that creates an instance of the subclass: 您还需要定义一个创建子类实例的方法:
abstract class Foo[X](protected[this] val s: Iterator[String]) {
self: X =>
def newSubclass(s: Iterator[String]): X
def apply(it: Iterator[String]): X = newSubclass(it ++ s)
}
class Bar(s: Iterator[String]) extends Foo[Bar](s) {
def newSubclass(s: Iterator[String]): Bar = new Bar(s)
}
Bar.apply
will have Bar
as its return type, without needing to be overriden. Bar.apply
将Bar
作为其返回类型,无需重写。
You can read more about F-bounded polymorphism at the Twitter Scala school . 您可以在Twitter Scala学校阅读有关F-bounded多态的更多信息。
Have looked through this article. 仔细阅读了这篇文章。 Seems it's what you want.
似乎这就是你想要的。 Quickly scetch out simple example(using
var
's in this example) 快速查看简单示例(在此示例中使用
var
)
class A(var s: String) {
def apply(a: String): this.type = {
s = "A" + a
this
}
}
class B(var s: String) extends A(s)
PS: Tried to use vals but it is impposible to call constructor in method which return type is this.type
. PS:尝试使用val但是在返回类型为
this.type
方法中调用构造函数是this.type
。 Maybe you'll find the solution)) 也许你会找到解决方案))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.