我想迭代使用反射的给定类的构造函数。 问题是我需要对每个元素执行一些操作,然后只返回匹配谓词的那些元素。下面的代码抛出异常斯卡拉flatMap over getConstructors方法(反射)
classOf[String].getConstructors.flatMap(x=> doSomething(x); if(predicate(x)) Some(x) else None)
例外:
argument expression's type is not compatible with formal parameter type;
found : java.lang.reflect.Constructor[_] => Iterable[java.lang.reflect.Constructor[?0(in value $anonfun)]] forSome { type ?0(in value $anonfun) }
required: java.lang.reflect.Constructor[_] => scala.collection.GenTraversableOnce[?B]
我不知道这是可以做到的理解,因为我需要调用做一些事情每个元素(不只是为持有谓词的):
for{
x <- c.getConsturctors
//doSomething(x) ??
if predicate(x)
}yield{
//doSomething(x) - only for the ones that holds the predicate
x
}
调用c.getMethods的作品,所以我猜它是与返回类型(数组[方法] VS阵[构造[_]])... ?
答:
flatMap - 阿列克谢·罗曼诺夫回答
的理解(有pamu的帮助下):
for{
x <- c.getConsturctors
_ = doSomething(x)
if predicate(x)
}yield x
需要更多关于'doSomething'和'predicate'的信息来告诉确切的错误 – pamu
它并不重要,可以说doSomething打印x和谓词只是返回true –