Home > Mobile >  Kotlin data class constructor, I met a can't solve the problem
Kotlin data class constructor, I met a can't solve the problem

Time:04-27





I'm going to the Java into Kotlin realize the same function, as shown in the following code, Java code creates two constructor initializes different attributes,
However, Kotlin use data class, cannot achieve the same function,

Initialization is only two, cannot have 3 kinds:
Table (date, time, price) or Table (date, priceBBB)
Now more Kotlin code 1 kind: the Table (date)

the main problem: now Kotlin code much a constructor, trouble arises at this extra main constructor, the constructor is not allowed to exist,
But I look at the data, it seems that the data class must have a constructor with parameters, although I can use the ordinary class implements like Java code, but this class is a data type,
Can you tell me how to solve? Is this is lack of Kotlin language logic?


Java:
 
Class Table {
Private String mDate;
Private String mTime.
Private double mPrice;
Private double mPriceBBBBBB;

The Table (String date, String time, double price) {
MDate=date;
MTime=time;
MPrice=price;
}

The Table (String date, double priceBBBBBB) {
MDate=date;
MPriceBBBBBB=priceBBBBBB;
}
}


Kotlin:
 
The data class Table (var date: String) {
Private var time: String?=null
Private var price=0.0
Private var priceBBBBBB=0.0

Constructor (date: String, time: String? Price: Double) : this (date) {
This. Time=time
This. Price=price
}

The constructor (date: String, priceBBBBBB: Double) : this (date) {
Enclosing priceBBBBBB=priceBBBBBB
}
}

CodePudding user response:

Kotlin can have default arguments, it is not necessary to overloaded constructor

CodePudding user response:

And attributes don't write in the main structure is not data fields, so it's best to a structure is enough
And don't understand you the meaning of design data classes so
  • Related