[英]How to declare variable/method type referred from the return type of another method
One of my method returns a Class type. 我的方法之一返回Class类型。 I wanna use this Class type as the parameter/return type of another method like:
我想将此Class类型用作另一个方法的参数/返回类型,例如:
class A {
def aClass: Class[_] = {
if (...){
classOf[String]
}else{
classOf[Int]
}
}
//Neither works
def kClass : aClass = {
//...
}
def kClass : Class[aClass] = {
//...
}
}
It complains Cannot resolve symbol aClass
. 它抱怨
Cannot resolve symbol aClass
。
Can this type of metaprogramming be achieved in Scala at all? 可以在Scala中完全实现这种类型的元编程吗?
you can define a type like this and can use that type. 您可以定义这样的类型并可以使用该类型。 right now you are putting a def as a type and there is no type like aClass defined so it's giving you compile time error that aClass can't be resolved.
现在,您将def作为类型,并且没有像aClass这样定义的类型,因此它给您带来了无法解析aClass的编译时错误。 I think that should work for you.
我认为这应该为您工作。
final type aClass = Class[_]
class A {
def aClass: Class[_] = {
if (true){
classOf[String]
}else{
classOf[Int]
}
}
//should works
def kClass: aClass = {
...
}
def kClass1: aClass = {
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.