如何正确地将Java建设者翻译成Kotlin?

时间:2019-04-21 16:46:27

标签: java android kotlin

我有一个Java类,它像这样扩展了AsyncTask:

class PostLocationTask extends AsyncTask<String, Void, String> {
    private String responseServer;
    private double latitude, longitude

    public PostLocationTask(double latitude, double longitude){
        this.latitude = latitude;
        this.longitude = longitude;
    }

}

我的目标是将代码翻译成Kotlin。现在我有了这个:

 companion object {
        class PostLocationTask internal constructor (context: PostLocationActivity): AsyncTask<String, Void, String?>(){

            private var responseServer = ""
            private var lat = 0.0
            private var lon = 0.0

            class PostLocationTask(var currentLat:Double, var currentLon:Double){
                lat = currentLat
                lon = currentLon
            }
        }
}

Android Studio用红色下划线标记了构造函数中的这两行,即“期望成员声明”。例如,将这两行包装在“ init {}”块内会将错误消息更改为“ Unresolved reference:lat”。

那么正确的翻译是什么?

4 个答案:

答案 0 :(得分:1)

尝试这些。希望对您有所帮助。

import android.os.AsyncTask
import android.os.Build
import android.support.annotation.RequiresApi

@RequiresApi(Build.VERSION_CODES.CUPCAKE)
internal class PostLocationTask(
    private val latitude: Double, 
    private val longitude: Double) : AsyncTask<String, Void, String>() {

        private val responseServer: String? = null

        override fun doInBackground(vararg strings: String): String? {
            return null
    }
}

答案 1 :(得分:0)

我想是

class PostLocationTask 
constructor(var latitude: Double, var longitude: Double) : AsyncTask<String, Void, String>() {
    private var responseServer: String? = null

}

答案 2 :(得分:0)

科特琳有two types of constructors。第一个是在类名之后,第二个是包含类的主体并被声明为“构造函数”

在你的情况下,我会做类似的事情

class PostLocationTask(
    var latitude: Double? = null, 
    var longitude: Double? = null
) : AsyncTask<String, Void, String>() {
    var responseServer: String? = null
    override fun doInBackground(vararg params: String?): String = getLocationFromServer()
}

答案 3 :(得分:0)

解决方案:这是Kotlin中正确的翻译代码。

inner class PostLocationTask(latitude: Double, longitude: Double) : AsyncTask<String, Void, String>() {
    private var responseServer: String? = null
    private var latitude: Double = latitude
    private var longitude: Double = longitude

    override fun doInBackground(vararg strings: String): String? {
        return null
    }
}

较短的版本

inner class PostLocationTask(private var latitude: Double, private var longitude: Double) : AsyncTask<String, Void, String>() {
    private var responseServer: String? = null

    override fun doInBackground(vararg strings: String): String? {
        return null
    }
}