Skip to content

Reflective call for Primitive + String fails with NoSuchMethodException #10469

Open
@sjrd

Description

@sjrd

In the following snippet, all asserts fail:

def concat(x: Any { def +(y: String): String }, y: String): String = x + y

assertEquals("Afoo", concat('A', "foo"))
assertEquals("5foo", concat(5.toByte, "foo"))
assertEquals("5foo", concat(5.toShort, "foo"))
assertEquals("5foo", concat(5, "foo"))
assertEquals("5foo", concat(5L, "foo"))
assertEquals("5.5foo", concat(5.5f, "foo"))
assertEquals("5.5foo", concat(5.5, "foo"))

Example error:

java.lang.NoSuchMethodException: java.lang.Integer.$plus(java.lang.String)
  at java.lang.Class.getMethod(Class.java:1786)
  at .reflMethod$Method1(<console>:10)
  at .concat(<console>:10)

Note that def +(s: String) is defined directly on the primitive classes (e.g., Int) and is supposed to be a primitive. This is not the case for Boolean and Unit, which receive their +(String) method from any2stringAdd, like any other class.

I always wondered why char/numeric primitive types had def +(s: String) defined directly. Probably the easiest fix is to just remove those definitions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions