One of my method returns a Class type. I wanna use this Class type as the parameter/return type of another method like:
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
.
Can this type of metaprogramming be achieved in Scala at all?
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. 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 = {
...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.