Kotlin: Programing is printing kotlin.unit

Viewed 533

My Kotlin Class will run but it prints out the words: kotlin.Unit. What do I need to change?

fun main(args: Array<String>) {
    var myDuck = Duck()
    println(myDuck.quack())
}
class Duck() {
    fun quack () {
        println("Quack, Quack, Quack")
    }
}
4 Answers

It is printing that because you are printing the return type of a function that does not return any value. If you are familiar with other languages it is the same as having a void return type.

In kotlin a funtion without a return type returns a unit type, and so when you print the return value of Duck::quack you are printing the string value of a Unit value.

The simplest solution is to not print the return value of Duck::quack; however, if you would like the prinlt to print the return of Duck::quak, it needs to return a useful value. For examle:

class Duck() {
    fun quack(): String {
        return "Quack, Quack, Quack"
    }
}

fun main(args: Array<String>) {
    var myDuck = Duck()

    println(myDuck.quack())
}

or more idiomatically:

class Duck() {
    val quack: String = "Quack, Quack. Quack"
}

fun main(args: Array<String>) {
    var myDuck = Duck()

    println(myDuck.quack)
}

It's anought to call

    myDuck.quack() 

wich has already println inside. Calling println(myDuck.quack()) prints type of myDuck.quack because it doesn't return any value.

1.prints "kotlin.Unit" if you don't specify the type

fun main(args: Array<String>) {
    var myDuck = Duck()
    println(myDuck.quack())
}
class Duck():String {
    fun quack () {
        return "Quack, Quack, Quack"
    }
}

Also as shortly:

fun main() {        
        println(Duck.quack())
    }

class Duck() {
    fun quack () = "Quack, Quack, Quack"
    }
Related