noncom
noncom

Reputation: 4992

Scala - mapping a list of integers to a method that receives java.lang.Object

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).

Upvotes: 4

Views: 1250

Answers (1)

Rex Kerr
Rex Kerr

Reputation: 167901

The type mismatch tells you exactly the problem: you can convert to java.lang.Integer but not to java.lang.Object. So tell it you want to ask for an Integer somewhere along the way. For example:

groupOfObjects.map(_.getNeededInt: java.lang.Integer).map(libraryObject.libraryMethod(_))

(The notation value: Type--when used outside of the declaration of a val or var or parameter method--means to view value as that type, if possible; value either needs to be a subclass of Type, or there needs to be an implicit conversion that can convert value into something of the appropriate type.)

Upvotes: 3

Related Questions