Infix function returning String


I’ve got simple class:

class Person(val name : String, val age : Int)

and infix function:

infix fun : Person) = “name {}”

For the following data:

println(Person("name",16) to Person ("last name", 0))

I want output like:

name lastname

But instead I’ve:

(com.other.Person@2d6e8792, com.other.Person@2812cbfa)

Why I’m getting result like that?


When we’re trying to define our own infix to function we must use @Override annotation, thanks ago IDE can import proper function and distinct your version of function from that build in.

infix fun : Person) = "$name  ${}"

Your println code is using Kotlin’s to infix function, which returns a pair. In IntelliJ you can put the cursor on to and press ctrl+Q to verify that.

I’m guessing your println code and your to function are in different packages, and you’re missing an import for your to in the println file. Kotlin’s to is imported by default so leaving out the import means Kotlin’s will be used.

If you don’t want to worry about importing it, then you can put your to function in the Person class. Functions in the class will always be used instead of extension functions


Thank you for your answer. That’s true, instead my infix function default’s launched.
Unfortunately placing infix within Person class, doesn’t change default mechanism.

Main function is within same package as function with infix

Here is a runnable version. It behaves as expected and invokes the custom method.

class Person(val name : String, val age : Int)

infix fun : Person) = "$name ${}"

fun main() {
    println(Person("name",16) to Person ("last name", 0))
1 Like