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.

2
  • 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. kotlinlang.org/docs/reference/… Commented Nov 17, 2019 at 8:59
  • Java doesn't care whether a function is marked as infix. Commented Nov 17, 2019 at 11:47

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Please note that the infix function in my case is outside the class. If it was inside, I know that it can be used like you mentioned. So, whatever you mentioned won't work in my case
@dileepkumarjami added a new idea to try.
I think that's the only work around. Thanks for your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.