how can i deal with the static parameters and static functions in kotlin?

258 views Asked by At
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
    }}}
1

There are 1 answers

1
Tenfour04 On

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 Companion instead of this to specify the companion's properties.

class C (a: String, b: String) {

    init {
        Companion.a = a
        Companion.b = b
    }

    companion object {
        @JvmField
        var a: String? = null
        @JvmField
        var b: String? = null

        @JvmStatic
        fun functionA(): JSONObject{
            val jsonObject = JSONObject()
            try {
                jsonObject.put(key1, a)
                jsonObject.put(key2, b)
            } catch (e: JsonException){
                //******
            }
            return jsonObject
        }
    }
}

Though I must say, I cannot recommend a design like this. It's a nasty abuse of statics.