Plaka
Plaka

Reputation: 173

Returning a class in Kotlin

class Wolf {
    var hunger = 10
    val food = "meat"

    fun eat() {
        println("The Wolf is eating $food")
    }
}

class MyWolf {
    var wolf: Wolf? = Wolf()

    fun myFunction() {
        wolf?.eat()
    }
}

fun getAlphaWolf(): Wolf? {
    return Wolf()
}

fun main(args: Array<String>) {
    var w: Wolf? = Wolf()

    if (w != null) {
        w.eat()
    }

    var x = w?.hunger
    println("The value of x is $x")

    var y = w?.hunger ?: -1
    println("The value of y is $y")

    var myWolf = MyWolf()
    myWolf?.wolf?.hunger = 8
    println("The value of myWolf?.wolf?.hunger is ${myWolf?.wolf?.hunger}")

    var myArray = arrayOf("Hi", "Hello", null)
    for (item in myArray) {
        item?.let { println(it) }
    }

    getAlphaWolf()?.let { it.eat() }

    w = null
    var z = w!!.hunger
}

This above code is extracted from a Kotlin textbook. I have problem with the following:

fun getAlphaWolf(): Wolf? {
     return Wolf()
}

As there is only a class called Wolf but no variable called Wolf in the code. I wonder if it is possible to return a class inside a function? What is the output if a class is returned inside a function?

Upvotes: 1

Views: 1818

Answers (2)

ordonezalex
ordonezalex

Reputation: 2745

If you are familiar with Java, then this Kotlin is equivalent to:

public class Application {
    public Wolf getAlphaWolf() {
        return new Wolf();
    }
}

So, in Kotlin you are calling the no-arguments constructor. If you want to return the class Wolf, then that is also possible:

fun getWolfClass(): KClass<Wolf> {
    return Wolf::class
}

Upvotes: 2

Iaroslav Postovalov
Iaroslav Postovalov

Reputation: 2453

In the following code, the primary constructor of class Wolf is called:

fun getAlphaWolf(): Wolf? {
     return Wolf()
}

So, getAlphaWolf returns a completely new instance of Wolf with default values: Wolf(hunger=10,food=meat).

Update: by the way, making the return type of this function nullable is redundant, because a new instance cannot be null.

Upvotes: 1

Related Questions