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
}

上面的代码摘自Kotlin教科书。
我有以下问题:
fun getAlphaWolf(): Wolf? {
     return Wolf()
}

因为在代码中只有一个名为Wolf的类,而没有名为Wolf的变量。
我想知道是否可以在函数内返回类吗?
如果在函数内部返回类,输出是什么?

最佳答案

如果您熟悉Java,则此Kotlin等效于:

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

因此,在Kotlin中,您正在调用无参数构造函数。如果要返回类Wolf,那么也可以:
fun getWolfClass(): KClass<Wolf> {
    return Wolf::class
}

关于kotlin - 在 Kotlin 重返类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60267758/

10-13 04:12
查看更多