Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple kotlin example prints kotlin.Unit when printing infix function outcome

Tags:

kotlin

I have the following really simple kotlin code to demo infix function package com.lopushen.demo.presentation

fun main(args: Array<String>) {
    print("Hello " x_x "world")
}


infix fun String.x_x(s: String) {
    println("$this x_x $s x_x")
}

And the expected outcome is

Hello  x_x world x_x
Process finished with exit code 0

Actual outcome below, what causes the program to print kotlin.Unit?

 Hello  x_x world x_x
 kotlin.Unit
 Process finished with exit code 0
like image 468
lopushen Avatar asked Mar 10 '23 10:03

lopushen


1 Answers

You have two print statements in your program. The one inside the x_x function prints the "Hello world" string, and the one in main prints the return value of the x_x function. The function doesn't have any return statements or a declared return type, so Kotlin infers Unit as its return type. The Unit type has a single value, kotlin.Unit, which is what your program prints.

like image 104
yole Avatar answered Mar 11 '23 22:03

yole