minhee
minhee

Reputation: 11

(Kotlin) How to initialize the HashMap without affecting the data

If you use hashmap, an error occurs due to an initialization problem. How should I do the initialization?

var requestHashMap:HashMap<String, RequestBody>
        
        requestHashMap["sound"] = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
        requestHashMap["content"] = content.toRequestBody("multipart/form-data".toMediaTypeOrNull())
        requestHashMap["img"] = getImageFile!!.asRequestBody("multipart/form-data".toMediaTypeOrNull())

Upvotes: 0

Views: 2088

Answers (2)

Daoud Mohamed
Daoud Mohamed

Reputation: 1

You must instantiate your HashMap after declaring it :

var requestHashMap = hashMapOf<String, RequestBody>()

requestHashMap["sound"] = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
requestHashMap["content"] = content.toRequestBody("multipart/form-data".toMediaTypeOrNull())
requestHashMap["img"] = getImageFile!!.asRequestBody("multipart/form-data".toMediaTypeOrNull())

In your code you have just declared a variable named requestHashMap of type HashMap

For more kotlin coding style :

var requestHashMap = hashMapOf<String, RequestBody>(
    "sound" to file.asRequestBody("multipart/form-data".toMediaTypeOrNull()),
    "content" to content.toRequestBody("multipart/form-data".toMediaTypeOrNull()),
    "img" to getImageFile!!.asRequestBody("multipart/form-data".toMediaTypeOrNull())
)

Upvotes: -1

Amani
Amani

Reputation: 3987

you can correct your code only by changing this line:

var requestHashMap: HashMap<String, RequestBody> = hashMapOf()

or changing all of your code to this:

var requestHashMap :HashMap<String, RequestBody> = hashMapOf(
        "sound" to file.asRequestBody("multipart/form-data".toMediaTypeOrNull()), 
        "content" to content.toRequestBody("multipart/form-data".toMediaTypeOrNull()), 
        "img" to getImageFile!!.asRequestBody("multipart/form-data".toMediaTypeOrNull()))

Upvotes: 2

Related Questions