Methods with the same name in the same class Java classes (in short, classes like ↓) that are a mixture of variable-length methods and fixed-length methods We investigated which one is called when called from Scala / Kotlin / Java with one argument.
public class CalledClazz {
public static void method(Object... args){
System.out.println("Variadic method" + Arrays.toString(args));
}
public static void method(Object args){
System.out.println("Fixed-length argument method" + args);
}
}
Behavior when one argument is passed
--Java => Basically, method (Object args)
is executed, but in some cases it becomes [strange behavior](called from #java).
--Kotlin => method (Object args)
is executed
--Scala => The variable length argument method (Object ... args)
is called ... so [How to call the fixed length argument Java method from Scala](fixed length argument java method from #scala) The method of calling) was also examined.
public class JavaClazz {
public static void main(String... args) throws IOException {
CalledClazz.method("Java");
CalledClazz.method(null);
Object s = null;
CalledClazz.method(s);
CalledClazz.method((Object)null);
}
}
Execution result
Fixed-length argument method Java
Variadic method null
Fixed-length argument method null
Fixed-length argument method null
If you pass null, will it come to variadic? Moreover, it is not an Object type array with 1 element, but null is passed ... What's more, if you declare a variable with some type with null and pass it, or cast it to Object, it will come to a fixed-length argument method ...
fun main() {
CalledClazz.method("Kotlin")
CalledClazz.method(null)
}
Execution result
Fixed-length argument method Kotlin
Fixed-length argument method null
It looks like a natural behavior.
object CallTestByScala extends App {
CalledClazz.method("Scala")
CalledClazz.method(null)
}
Execution result
Variadic method[Scala]
Variadic method[null]
Why is it an array and the variadic method is called?
val f: Object => Unit = CalledClazz.method
f("Scala")
Fixed-length argument method Scala
It came to come out.
In this way, declaring the type of a function without relying on type inference seems to be called as intended. Is there any other way?
By the way,
val f: Object => Unit = CalledClazz.method
f("Scala", "aaaaa")
Then, the method with fixed-length argument is called, and one value of Tuple2 type is passed.
Fixed-length argument method(Scala,aaaaa)
Will come out.
From Scala's point of view, method (Object ... args)
seems to be treated as an iterative parameter.
If you want to pass scala.List
to a Java variable length method ** as intended **,
CalledClazz.method(List("a","b","b"): _*)
Must be.
If you do not add it, it will be treated as an array with 1 element, with one object called List ("a", "b", "b")
as an element.
Variadic method[List(a, b, b)]
Will come out.
Scala: How to pass as a List to Repeated Parameters \ (Repeated Parameters ) -Qiita
Recommended Posts