Chu*_*ulo 5 java types objective-c
在Objective-C中,instancetype可以用作返回类型的返回类型,这些方法返回它们被调用的类的实例(或该类的子类).
instancetypeJava中的等价物是什么?
如果你的意思是这样的:
class Vehicle {
instancetype doNothing() {return this;}
}
class Car extends Vehicle {}
Car c = new Car().doNothing(); // no compile errors here
Run Code Online (Sandbox Code Playgroud)
没有同等的。
有时使用的一种解决方法是将类型作为泛型参数传递:
class Vehicle<instancetype> {
instancetype doNothing() {return this;}
}
class Car extends Vehicle<Car> {}
Car c = new Car().doNothing(); // works
Run Code Online (Sandbox Code Playgroud)
但是这样你就不能在Vehicle没有到处收到警告的情况下使用该类型(它必须是Vehicle<?>)。