我想迭代使用反射的給定類的構造函數。 問題是我需要對每個元素執行一些操作,然後只返回匹配謂詞的那些元素。下面的代碼拋出異常斯卡拉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 –