简体   繁体   English

在Scala中,有没有一种方法可以指定返回类型应该与方法调用者的类型匹配?

[英]In Scala is there a way to specify that the return type should match the type of the method caller?

For example, I have a class called Foo 例如,我有一个名为Foo的类

abstract class Foo {
    def f(): ??? = { ... }
}
class Bar extends Foo {
    ...
}
class Baz extends Foo {
    ...
}

What I'd like is a way for f to return a Bar when it's called by Bar, and a Baz when it's called by Baz. 我想要的是f由Bar调用时返回Bar的方法,而由Baz调用时返回Baz的方法。 Both Bar and Baz would have the same constructor, so the code in f would be the same both times, except for whether I have to say new Bar(...) or new Baz(...). Bar和Baz都具有相同的构造函数,因此f中的代码两次都相同,除了我必须说new Bar(...)还是new Baz(...)。 Is there any way to say new TypeOfWhateverClassIsCallingMe(...)? 有什么办法说新的TypeOfWhateverClassIsCallingMe(...)?

Sounds like you want F-Bounded types. 听起来像您想要F界限类型。 You'll still have to implement it for all subclasses however, as the parent class has no knowledge of the child constructors (A "Mammal" does not know how to make a "Cat"). 但是,您仍然必须为所有子类实现它,因为父类不了解子构造函数(“哺乳动物”不知道如何制作“猫”)。

abstract class Foo[T <: Foo[T]] {
    def createMe(): T
}

class Bar extends Foo[Bar] {
    override def createMe() = new Bar
}

class Baz extends Foo[Baz] {
    override def createMe() = new Baz
}

This basically gives you compile-time safety, all children of Foo need to implement a method that creates something of its own class. 这基本上为您提供了编译时的安全性, Foo所有子级都需要实现一个创建自己类的方法。

In-depth discussion here . 这里深入讨论。

假设您要调用该方法的具体子类的类型(我不会将其称为“方法调用者的类型”,而是“被调用者的类型”),则可以执行

def f(): this.type = ???

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM