Let us say that I have a class in Kotlin like below
Also, let us define an infix function generateEmailWithDomain which generates the email address based on the name with the given domain
class Person(var name: String) {}
infix fun Person.generateEmailWithDomain(domain: String): String = "${this.name}@$domain.com"
Now, as it is said that Kotlin is 100% interoperable with Java, how can I make use of this infix function in a JAVA class?
The above usage of infix may be inappropriate but I would like to know how this can be used in Java.
Please correct my understanding if it is wrong.
Based on the docs ( https://kotlinlang.org/docs/reference/functions.html#infix-notation ), infix
seems to be mere syntactic sugar to me, as even the example there shows two ways of calling such function:
class MyStringCollection {
infix fun add(s: String) { /*...*/ }
fun build() {
this add "abc" // Correct
add("abc") // Correct
//add "abc" // Incorrect: the receiver must be specified
}
}
So, from Java I would simply use the second one, tailored to your case that would be
String result = somePerson.generateEmailWithDomain(someString);
(as defining an extension function "outside" as Person.generateEmailWithDomain()
is also just an optional possibility, when calling that will be a method of an actual Person
object)
static
method then, with two arguments, the first being the receiver, and the second one is the actual argument.
String result = Person.generateEmailWithDomain(somePerson, someString);
If you want to see how your code looks like in java and you use Intellij Idea, you can go Tools -> Kotlin -> Show Kotlin bytecode -> decompile.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.