“Normally, if you write a Kotlin function with def...
# getting-started
b
“Normally, if you write a Kotlin function with default parameter values, it will be visible in Java only as a full signature, with all parameters present.” What is a signature?
j
The signature of a function is kind of its public declaration: its name, argument list, return type. In this context, it means that from Java it will be visible as a function with all arguments (those with default values will still appear to java as part of the mandatory arguments)
👍 2
k
"Two of the components of a method declaration comprise the _method signature_—the method's name and the parameter types."
They should add the return type in there as well
👍 3
b
thank guys!
r
Return type isn’t part of the signature - you can’t have two methods with the same name & parameter types but different return types.
🤷‍♂️ 1
p
The other thing to add is that you can annotate the method with
@JvmOverloads
and the compiler will spit out, as the name implies, sequential JVM overloads with your default arguments specified. Nice for Java consumers of Kotlin code, otherwise unnecessary
j
@Rob Elliot yeah I guess it depends on context, but you're right technically in Java it's not included behind the term "signature"
e
on JVM, return type is technically part of the signature, and you can even have overloads that differ in return type only in bytecode, but Java and Kotlin disallow that
c
@Rob Elliot Only in Java. Kotlin allows multiple overloads that differ only by their return type. To use them on Kotlin/JVM, you'll need
@JvmName
, but on Kotlin/JS it's supported by default.
r
Kotlin 1.5.31. The following does not compile for me
Copy code
package bar

@JvmName("foo1")
fun foo(): String {
  println("foo1")
  return ""
}
@JvmName("foo2")
fun foo(): Int {
  println("foo2")
  return 1
}

fun main() {
  val x: Int = foo()
}
Error message:
Copy code
Bar.kt: (3, 1): Conflicting overloads: public fun foo(): String defined in bar in file Bar.kt, public fun foo(): Int defined in bar in file Bar.kt
Same in a kotlin/js IR project using node.js.
e
Kotlin can handle overloads that Java can't, for example
Copy code
@JvmName("fooInt")
fun foo(list: List<Int>)
@JvmName("fooString")
fun foo(list: List<String>)
which would be erased to the same signature without
@JvmName
, but it does not allow overloading by return type
c
Sorry, it's a big more subtle than what I was remembering. https://stackoverflow.com/a/52020972/5666171 Kotlin does allow multiple methods that differ only by their return type, if one of them uses generics.
e
well, kinda. if you wrote
Copy code
fun foo(): String = TODO()
fun <T: String> foo(): T = TODO()
they have the same erased signature on JVM, so Kotlin will disallow that, as well as disallowing other cases even with different type parameters such as
Copy code
fun <T: String> foo(bar: Any): T = TODO()
fun <U, V : Any> foo(bar: V): U = TODO()
even though they have different JVM signatures