Łukasz Kiełczykowski
Posted on January 26, 2022
Used Kotlin plugin:
203-1.5.30-release-411-AS7717.8
Used Kotlin version:1.5
It was a calm beginning of a workday. I sat down to my computer and I started coding. I needed to add a custom Exception
class to have logs and a code more readable. You've probably done this many many times.
Usual exception in Kotlin:
data class SomeCustomException(
val explanation: String
) : Exception(
message = "Oh, something broke because $explanation"
)
Now, stop for a second and try to figure out what's wrong with that code.
The code above is not marked by the Android Studio as an error. However, when you try to compile this, it will fail with a message Cannot find a parameter with this name: message
.
I removed the name message
from parameters
data class SomeCustomException(
val explanation: String
) : Exception(
"Oh, something broke because $explanation"
)
and it compiles just fine. The question is why?
Apparently, this is a known issue. The IDE treats the Exception
class as Kotlin's, but it's just an alias for Java's Exception
class. The IDE would have shown you an error, if you had used Java import:
data class SomeCustomException(
val explanation: String
) : java.lang.Exception(
message = "Oh, something broke because $explanation" // pointed out as an error by the IDE
)
Maybe for some. of you it's obvious - duh, of course it will fail 🧐 - but I added the named parameter without even thinking.
I hope you are having a great day, without surprising failures ✌🏻
Posted on January 26, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 21, 2024