beatngu13
beatngu13

Reputation: 9453

Scala List[Int] becomes List<Object> in Java

I have the following list defined within a Scala object:

object Foo {
    val bar = List(1, 2, 3)
}

Which seems to become a scala.collection.immutable.List<Object> when I try to use it from Java. As a consequence, I have to use getters like Foo.bar().apply$mcII$sp(i) or apply with a cast to Integer/int.

Why is the generic type Object and not Integer? This also seems to be only the case for types that exist as Java primitives; List[MyType] becomes List<MyType> in Scala.

Upvotes: 5

Views: 421

Answers (3)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149656

This happens due to the fact that Java does not support primitive types in generic types, generics are a compile time construct only in Java, they do not exist in JVM bytecode, thus they must be convertible to Java's Object type, which primitives cannot.

If we compile the code using the -Xprint:jvm flag, you can see that List[Int] actually compiles to the non generic List:

package com.yuvalitzchakov.github {
  object Foo extends Object {
    private[this] val bar: List = _;
    <stable> <accessor> def bar(): List = Foo.this.bar;
    def <init>(): com.yuvalitzchakov.github.Foo.type = {
      Foo.super.<init>();
      Foo.this.bar = scala.collection.immutable.List.apply(scala.Predef.wrapIntArray(Array[Int]{1, 2, 3}));
      ()
    }
  }
}

If Foo.bar was a List[Integer], this would yield a List<Integer> in Java, instead of List<Object>

Upvotes: 2

Mr.Turtle
Mr.Turtle

Reputation: 3090

I have experienced a somewhat similar issue with Swagger not responding well to Scala.

I don't know why, but this bug/feature is related to Java's primitives that dont't have setters and getters (like objects). Since the Java compiler can't find a suiting object, it just compiles it down to Object.

Scala collections have made converters to fix this: https://docs.scala-lang.org/overviews/collections/conversions-between-java-and-scala-collections.html

The only workaround I can think about is to use: Foo.bar.toJava

Sources: Deserializing Scala list with Jackson

https://stackoverflow.com/a/52581955/2291510

Spring RequestParam formatter for Scala.Option

Good luck!

Upvotes: 2

Vladimir Berezkin
Vladimir Berezkin

Reputation: 3599

Try to use collection decorator asJava:

val javabar = bar.asJava

Upvotes: 1

Related Questions