Home > other >  generic "type expected" error message in kotlin
generic "type expected" error message in kotlin

Time:12-21

I'm learning Kotlin and I've written the following code and I'm getting a compile error.

Is there any solution?

class CommonResponse<T>(
    var result: Result, var data: T?, var message: String?, var errorCode: String?
) {

    companion object {

        fun <T> success(): CommonResponse<*> {
            return CommonResponse(Result.SUCCESS, null, null, null)
        }

        fun <T> success(data: T): CommonResponse<*> {
            return CommonResponse(Result.SUCCESS, data, null, null)
        }
}
val success = CommonResponse.success<>() // compile error!! "Type expected"

I don't know why this error occurs.

CodePudding user response:

I'm not quite sure what it is you are trying to accomplish here, but if you want it to pass compile check, you can just simply change the generic type you want to Any.

  CommonResponse.success<Any>()

will do just fine.

CodePudding user response:

In your case success() is not related to any specific T, so you should not define T for success():

val success = CommonResponse.success()

fun success(): CommonResponse<*> { ... }

As a side note, CommonResponse<*> is probably not the best type here. <*> means: "type of the data is unknown". Your case is more like: "there is no data at all", so it makes more sense to use CommonResponse<Unit> or alternatively CommonResponse<Nothing>. It depends on how do you like to expose the information that there is no data. In the first case data property should return the Unit object, in the second case accessing data should throw an exception.

  • Related