Scala flatMap over getConstructors method (reflection) -
i'm trying iterate on constructors of given class using reflection. problem need each element , return ones matches predicate. following code throws exception
classof[string].getconstructors.flatmap(x=> dosomething(x); if(predicate(x)) some(x) else none)
the exception:
argument expression's type not compatible 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]
i'm not sure if can done comprehension because need call on each element(not ones holds predicate):
for{ x <- c.getconsturctors //dosomething(x) ?? if predicate(x) }yield{ //dosomething(x) - ones holds predicate x }
calling c.getmethods works i'm guessing has return type(array[methods] vs array[constructor[_]])...?
answer :
flatmap - alexey romanov answer
for comprehension(with of pamu):
for{ x <- c.getconsturctors _ = dosomething(x) if predicate(x) }yield x
due details of type inference implementation, scala ends iterable[java.lang.reflect.constructor[a]] forsome { type }
want iterable[java.lang.reflect.constructor[a] forsome { type }]
(or shorter, iterable[java.lang.reflect.constructor[_]]
). annotating type should work:
c.getconstructors.flatmap { x => dosomething(x) (if (predicate(x)) some(x) else none): option[constructor[_]] }
but must admit don't see why problem arises.
Comments
Post a Comment