简体   繁体   中英

How to use an infix function of a Kotlin class in Java?

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)


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);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM