繁体   English   中英

如何在 kotlin 中初始化 object 数组

[英]How can I initialize object array in kotlin

我像这样制作了 object class 数组:

private val stockList= MutableList(50){Stock()}

库存 class 有一些变量,如namenumberprice等。那么如何初始化这个 object class 列表?

    stoke *item = new stoke[numb];
    for (int a = 0; a < numb; a++) {
        char* tmp = new char[100];
        int price = 0, number = 0;
        cout << a + 1 << ". name price number (using spacebar)";
        cin >> tmp >> price >> number;
        item[a].setproduct(tmp, price, number);

    } 

当我使用c++时,我通过这种方式(consol)获得了class成员vlaue。

        val editTitle = dialogView.findViewById(R.id.editTitle) as EditText
        val editNumber = dialogView.findViewById(R.id.editnumber) as EditText
        val editBuy = dialogView.findViewById(R.id.editbuy) as EditText
        val editSell = dialogView.findViewById(R.id.editsell) as EditText

以下是现货 class

    class stock{
    var name:String?=null
    var buyprice:Int=0
    var sellprice:Int=0
    var important:Boolean = false
    var number:Int = 0}

我应该制作 class 构造函数吗?

当我使用布局小部件editText获取这些值时,如何将这些值放入stocklist

不太确定你的问题是什么,我不知道 Android。但这里有一个构建对象列表的示例,从 STDIN 读取值:

data class Stock(
    var name: String? = null,
    var price: Int = 0,
    var important: Boolean = false,
    var number: Int = 0
)


fun main() {
    print("How many items? ")
    val itemCount = readLine()!!.toInt()

    val items: List<Stock> = (1..itemCount).map {
        print("$it. name price number (using spacebar): ")
        val (inputName, inputPrice, inputNumber) = readLine()!!.split(' ')
        Stock(
            name = inputName,
            price = inputPrice.toInt(),
            number = inputNumber.toInt(),
        )
    }
    println(items)
}

示例 session:

How many items? 3
1. name price number (using spacebar): a 1 2
2. name price number (using spacebar): b 3 4
3. name price number (using spacebar): c 5 6
[Stock(name=a, price=1, important=false, number=2), Stock(name=b, price=3, important=false, number=4), Stock(name=c, price=5, important=false, number=6)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM