0

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.

dileepkumar jami
  • 2,185
  • 12
  • 15
  • 3
    Yes, you can. An extension function, whether it's infix or not, is compiled to a static method of a class. You call that static method in Java. https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#package-level-functions – JB Nizet Nov 17 '19 at 08:59
  • Java doesn't care whether a function is marked as infix. – Alexey Romanov Nov 17 '19 at 11:47

1 Answers1

2

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)


Ok, I was too optimistic. Based on https://stackoverflow.com/a/28364983/7916438, I would expect you to face a 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);
tevemadar
  • 12,389
  • 3
  • 21
  • 49