When you're working with GraalJS and want to call a Java (or Kotlin, since Kotlin compiles to Java bytecode) function from JavaScript, the parameters you pass from JavaScript need to be compatible with the Java method's parameter types.
If you have a Kotlin (or Java) function that takes a Float as a parameter, and you're calling it from JavaScript, you need to ensure that the value you pass is correctly interpreted as a Float.
Directly Passing a Number from JavaScript
GraalJS automatically converts JavaScript numbers to Java double when calling Java methods. Unfortunately, it doesn't directly convert to float. So, if you have a method like this in Kotlin:
class MyClass {
fun myMethod(floatValue: Float) {
println("Received float value: $floatValue")
}
}
And you're trying to call it from JavaScript like this:
var myObject = Java.type('your.package.MyClass').new();
myObject.myMethod(1.2);
You might encounter issues because GraalJS is trying to convert 1.2 (a JavaScript number) to a double, which isn't directly compatible with float.
Using Kotlin's .toFloat() in GraalJS
You can't directly call Kotlin's .toFloat() from GraalJS because .toFloat() is a Kotlin extension function on Kotlin's Number class (or more specifically, it's defined on various numeric types), and GraalJS is executing JavaScript, not Kotlin.
However, you can achieve a similar effect by using JavaScript's parseFloat() or simply passing the number as is and handling the conversion on the Java/Kotlin side.
Handling Conversion on the Java/Kotlin Side
One straightforward solution is to change your Kotlin method to accept a Double (or double in Java) instead of a Float, and then convert it to Float inside the method:
class MyClass {
fun myMethod(doubleValue: Double) {
val floatValue = doubleValue.toFloat()
println("Received float value: $floatValue")
}
}
Then, calling myMethod(1.2) from JavaScript should work as expected.
Alternative: Overloading the Method
Another approach is to overload your method to accept a Double (since GraalJS will pass the JavaScript number as a Double):
class MyClass {
fun myMethod(floatValue: Float) {
println("Received float value: $floatValue")
}
@JvmName("myMethodDouble") // To avoid Kotlin compiler error due to JVM signature clash
fun myMethod(doubleValue: Double) {
myMethod(doubleValue.toFloat())
}
}