Working in Scala-IDE, I have a Java library, in which one of the methods receives java.lang.Object
. And I want to map a list of Int
values to it. The only solution that works is:
val listOfInts = groupOfObjects.map(_.getNeededInt)
for(int <- listOfInts) libraryObject.libraryMethod(int)
while the following one:
groupOfObjects.map(_.getNeededInt).map(libraryMethod(_)
and even
val listOfInts = groupOfObjects.map(_.getNeededInt)
val result = listOfInts.map(libraryObject.libraryMethod(_))
say
type mismatch; found : Int required: java.lang.Object Note: an implicit exists from scala.Int => java.lang.Integer, but methods inherited from Object are rendered ambiguous. This is to avoid a blanket implicit which would convert any scala.Int to any AnyRef. You may wish to use a type ascription:
x: java.lang.Integer
.
and something like
val result = listOfInts.map(libraryObject.libraryMethod(x => x.toInt))
or
val result = listOfInts.map(libraryObject.libraryMethod(_.toInt))
does not work also.
1) Why is it happening? As far as I know, the for
and map
routines do not differ that much!
2) Also: what means You may wish to use a type ascription: x: java.lang.Integer
? How would I do that? I tried designating the type explicitly, like x: Int => x.toInt
, but that is too erroneus. So what is the "type ascription"?
UPDATE:
The solution proposed by T.Grottker, adds to it. The error that I am getting with it is this:
- missing parameter type for expanded function ((x$3) => x$3.asInstanceOf[java.lang.Object])
- missing parameter type for expanded function ((x$3) => x$3.asInstanceOf{#null#}[java.lang.Object]{#null#}) {#null#}
and I'm like, OMG, it just grows! Who can explain what all these <null>
things mean here? I just want to know the truth. (NOTE: I had to replace <> brakets with # because the SO engine cut out the whole thing then, so use your imagination to replace them back).
listOfInts.map(x => libraryObject.libraryMethod(x.toInt))
should work – elbowichint
and not an object? In java land you can't do autounboxing and "widening" at the same time, not sure if the same applies to Scala thou. – Emil H