Koykoy200078
Koykoy200078

Reputation: 21

Expression 'return length as Int.toString' of type 'Nothing' cannot be invoked as a function

private String getFileSize(long length) {
    DecimalFormat df = new DecimalFormat("######0.0");
    if (length < 1024.f) {
        return (int) length + " B";
    } else if (length < 1024 * 1024.f) {
        return df.format(length / 1024.f) + " KB";
    } else if (length < 1024 * 1024 * 1024.f) {
        return df.format((length / 1024.f / 1024.f)) + " MB";
    }
    return df.format(length / 1024.f / 1024.f / 1024.f) + " GB";
}

Original Code

private fun getFileSize(length: Long): String {
    val df = DecimalFormat("######0.0")
    if (length < 1024f) {
        return length as Int.toString() + " B"
    } else if (length < 1024 * 1024f) {
        return df.format(length / 1024f.toDouble()) + " KB"
    } else if (length < 1024 * 1024 * 1024f) {
        return df.format((length / 1024f / 1024f).toDouble()) + " MB"
    }
    return df.format(length / 1024f / 1024f / 1024f.toDouble()) + " GB"
}

Code After Java to Kotlin Converstion

return length as Int.toString() + " B"

Error: Expression 'return length as Int.toString' of type 'Nothing' cannot be invoked as a function. The function 'invoke()' is not found. Unresolved reference: toString.

Upvotes: 1

Views: 55

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

You are calling Int.toString method as datatype.toString method that does not achieve anything so instead use String interpolations as

return "$length B"

or use toString as

return length.toString() + " B"

You can also use expressions with string interpolation inside ${expression} as

return "${df.format(length / 1024.f)} KB";

Upvotes: 1

Related Questions