public class C {
public static string a;
public static string b;
public C(String a, String b){
this.a=a;
this.b=b;
}
public void addString(){
String result=a+b;
}
public static JSONObjet functionA(){
JSONObject jsonobject = new JSONObject();
try {
jsonobject.put(key1, a);
jsonobject.put(key2,b);
} catch(JsonException e){
******}
return jsonobject;}}
if put the parameters before init{}, then the functionA() can not recognize the a and b. If put the parameters into the companion object{}, the init can not recognize the a and b. How to convert this class to kotlin? what is your suggestion?
Class C{
fun addString(){
var result:String=a+b
}
init {
this.a=a
this.b=b
}
companion object {
var a:String?=null
var b:String?=null
@JVMStatic
fun functionA(): JSONObject?{
var jsonobject = JSONObject()
try {
jsonobject.put(key1, a)
jsonobject.put(key2,b)
} catch(JsonException e){
******}
return jsonobject
}}}
The strict equivalent of your code is similar to what you have, except that you're missing the constructor parameters, and you need to use
Companioninstead ofthisto specify the companion's properties.Though I must say, I cannot recommend a design like this. It's a nasty abuse of statics.