Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is getMessage() an unresolved reference in Kotlin with an Exception class?

Tags:

kotlin

Kotin documentation says that "All exception classes in Kotlin are descendants of the class Throwable. Every exception has a message, stack trace and an optional cause."

The Java documentation for Throwable shows a getMessage() method. But the Kotlin documentation for Throwable does not have a getMessage(). So this code:

fun main(args: Array<String>)
{
   try
   {
      println("args size: ${args.size}");
   }
   catch (e: Exception)
   {
      println(e.getMessage())
      System.exit(1)
   }
}

gives me this compile error:

test_exception.kt:12:17: error: unresolved reference: getMessage
      println(e.getMessage())
                ^

suggesting that I am using a Kotlin Exception class derived from a Kotlin Throwable class.

However, if I change getMessage() to toString() and add a throw:

fun main(args: Array<String>)
{
   try
   {
      println("args size: ${args.size}");
      throw Exception("something went wrong")
   }
   catch (e: Exception)
   {
      println(e.toString())
      System.exit(1)
   }
}

I get this message:

java.lang.Exception: something went wrong

Which seems to say that the Exception class is NOT a Kotlin Exception class - but the java version which has a getMessage() method and I shouldn't get a compile error when I try to use it.

like image 821
Scooter Avatar asked Jun 17 '17 04:06

Scooter


1 Answers

There is no other Throwable except for java.lang.Throwable. This class is used both by Java and by Kotlin programs.

The fact that Throwable has an entry in the Kotlin documentation suggests that this is a special compiler "alias". That means that for all intents and purposes it is a Kotlin class, instances of which are represented by java.lang.Throwable. Black magic.

TL;DR:

The equivalent of e.getMessage() in Kotlin is e.message, which is described in the docs as open val message: String?.

Since Throwable is not used directly from Java, but mapped to Kotlin, you cannot use the Java notation e.getMessage() for the property. Here is more about mapped types: http://kotlinlang.org/docs/reference/java-interop.html#mapped-types

like image 188
voddan Avatar answered Nov 13 '22 05:11

voddan