I am new to kotlin programming and getting one initialization error while trying to close BufferedReader instance. Here is the kotlin class:
package first.kot.kotprac
import android.os.AsyncTask
import android.util.Log
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.net.ResponseCache
import java.net.URL
import javax.net.ssl.HttpsURLConnection
class MyAsyncTask : AsyncTask<Void, Void, Void>() {
private val TAG = "MyAsyncTask"
private var responseData = ""
override fun doInBackground(vararg params: Void?): Void? {
val reader : BufferedReader
try{
val url= URL("vvv")
val conn = url.openConnection() as HttpsURLConnection
val responseCode = conn.responseCode
Log.e(TAG,"Response code: "+responseCode);
if(responseCode == HttpsURLConnection.HTTP_OK){
reader = BufferedReader(InputStreamReader(conn.inputStream))
var sb = StringBuilder()
reader.lineSequence().forEach {
sb.append(it+"\n")
}
responseData = sb.toString()
}
}catch (e: Exception){
e.printStackTrace()
}
finally {
if(reader!=null)
reader.close() // Error line
}
return null
}
}
I have gone through the following thread:
https://stackoverflow.com/questions/41537638/assignment-not-allowed-in-while-expression
but I am not getting how the second way in the ticked answer will make sure that buffer is closed and my main concern is to solve the current issue too. Please help me to solve this problem.