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

Kotin's documentation states: "All exception classes in Kotlin are descendants of the Throwable class. Every exception has a message, a stack trace, and an optional reason."

The Java documentation for Throwable shows the getMessage () method. But Kotlin documentation for Throwable doesn't have 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 compilation error:

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

      

assuming I am using the Kotlin exception class derived from the Kotlin Throwable class.

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

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 am getting this message:

java.lang.Exception: something went wrong

      

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

+3


source to share


1 answer


There is no other Throwable

but java.lang.Throwable

. This class is used by both Java and Kotlin programs.

The fact that it Throwable

has an entry in the Kotlin documentation suggests that it is a special compiler "alias". This means that for all intents and purposes, this is the Kotlin class that is instantiated java.lang.Throwable

. Black magic.

TL; DR:



The e.getMessage()

Kotlin equivalent is e.message

, which is described in the docs as open val message: String?

.

Since it is Throwable

not used directly from Java, but displayed in Kotlin, you cannot use Java notation e.getMessage()

for a property. More on mapped types: http://kotlinlang.org/docs/reference/java-interop.html#mapped-types

+5


source







All Articles