Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch: inferred type is String but Charset was expected in kotlin

I have the following code in my main activity:

var qNa_list = parseQuestions(loadJSONFromAsset("qna_list.json"))


fun loadJSONFromAsset(file_name:String): String? {
    var json: String? = null
    try {

        val isis = assets.open(file_name)

        val size = isis.available()

        val buffer = ByteArray(size)

        isis.read(buffer)

        isis.close()

        json = String(buffer, "UTF-8")


    } catch (ex: IOException) {
        ex.printStackTrace()
        return null
    }

    return json

}

When I try to compile it I get the following error.

I fixed some other errors caused due to nullables, but this one is something I'm unable to decode.

Error:(127, 35) Type mismatch: inferred type is String but Charset was expected

I have changed some of the values to nullable to accomidate for the errors, but the json = String(buffer, "UTF-8") (UTF-8) is always underlined in red.

like image 509
Kotlinboy Avatar asked Nov 09 '17 09:11

Kotlinboy


2 Answers

This seems to have solved the issue.

It seems I need to specify the Charset type object and not a string like UTF-8.

1st method as mentioned by @Maroš Šeleng

Charset.forName("UTF-8")

Or, specify Charset.UTF_8

val charset: Charset = Charsets.UTF_8

json = String(buffer, charset)
like image 68
Kotlinboy Avatar answered Nov 14 '22 17:11

Kotlinboy


According to javadoc, String contructor accepts the second argument of type Charset as seen here . You can use Charset.forName(String) static method to create your Charset.

like image 20
Maroš Šeleng Avatar answered Nov 14 '22 17:11

Maroš Šeleng