【问题标题】:How to print the value of getter method如何打印getter方法的值
【发布时间】:2018-09-16 11:12:40
【问题描述】:

我在 Eclipse 中创建了以下示例。我正在关注一个教程,它提到我可以使用print(s1.captain) 来打印船长姓名。本教程想展示kotlin自动生成settersgetters

在我的代码中,打印语句不打印任何东西

主要

fun main(args : Array<String>) {
    var s1 = Stronghold1("JJ",7)
    print(s1.captain)
}

要塞

abstract class Stronghold(name: String, location: String)

要塞1

class Stronghold1(captain: String, capacity: Int) : Stronghold("GerMachine", "Bonn")

【问题讨论】:

    标签: java kotlin kotlin-android-extensions kotlin-extension


    【解决方案1】:

    在 Kotlin 中,构造函数参数只有在标记为 valvar 时才会转换为属性。在您的情况下,captaincapacitynamelocation 只是构造函数的参数。它们不会被制成属性。

    要将captaincapacity 作为属性,请将val 添加到它们:

    class Stronghold1(val captain: String, val capacity: Int) : Stronghold("GerMachine", "Bonn")
    //                ^^^                  ^^^
    //                add                  add   
    

    您可能也想对Stronghold 做同样的事情:

    abstract class Stronghold(val name: String, val location: String)
    //                        ^^^               ^^^
    //                        add               add
    

    【讨论】:

    • 您可能还想将它们转换为数据类以获得默认的toString 实现
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多