Hello. I have a question about kotlin value/inline classes. Not sure if this is the proper channel - please direct me to a better one if appropriate!
Given a kotlin value class like
Copy code
@JvmInline
value class Password private constructor(val password: String) {
companion object {
@JvmStatic
@JvmName("of")
fun of(password: String) = Password(password)
}
}
and a corresponding java class
Copy code
public class JavaClass {
public void func(Password word) {
System.out.println(word);
}
public void invoke() {
String s = "test";
this.func(Password.of(s));
}
}
I get an error on the invocation of
this.func
claiming that the required type is Password and I have provided String. Is there any work around? Or can value classes not be used as parameters for java methods?
e
ephemient
12/22/2023, 9:33 PM
it doesn't make sense to expose a Java parameter of type `Password`; the way Kotlin handles it, it's all
String
at runtime (except when boxed)
s
Stephan Schröder
12/22/2023, 9:33 PM
generally inline classes are (mostly) optimized away at runtime, so I can see how the java compiler might "not get it".
See what happens if you make func a vararg method:
Copy code
public void func(Password... words) {
if(words.length!=1){throw new IllegalArgumentException();}
var word = words[0];
System.out.println(word);
}
since arrays actually retain their generic type.
e
ephemient
12/22/2023, 9:34 PM
this does mean that Java doesn't get type safety benefits from value classes