3

Context

Kotlin's kotlin.String type is currently defined as follows (1.1.2):

public class String : Comparable<String>, CharSequence {
    companion object {}

    // Operator and override function definitions.
}

Some extensions defined on kotlin.String cast the receiving instance to the java.lang.String type to forward method invocations. For example (1.1.2):

@kotlin.internal.InlineOnly
public inline fun String.toLowerCase(): String = (this as java.lang.String).toLowerCase()

However, nothing in the kotlin.String type definition makes it clear to me that this cast is guaranteed to succeed.

Questions

  • Is there any way to easily determine if any given Kotlin type is mapped to a corresponding Java type in this manner?
  • Where does this conversion actually happen? (Looking for a link to the relevant source code if possible.)
stkent
  • 19,772
  • 14
  • 85
  • 111
  • `Where does this conversion actually happen?` What do you mean by that? Kotlin's `String` is basically a typealias of Java's `java.lang.String` – Mibac Jun 27 '17 at 18:53
  • @Mibac how do you know that? It's not obvious from the source code, as I showed above, so that "aliasing" must occur somewhere. I'm looking for the _where_ part :) – stkent Jun 27 '17 at 18:56
  • 1
    I think there's a bit of compiler magic involved to make strings work like Java strings. I couldn't find documentation for it right now though. – marstran Jun 27 '17 at 20:14

1 Answers1

3

In Kotlin/JVM kotlin.String is one of the mapped types - a type that is represented with some existing JDK class in runtime.

Therefore a cast between kotlin.String and java.lang.String succeeds in runtime, even though these are two unrelated types from the point of Kotlin type system.

Ilya
  • 21,871
  • 8
  • 73
  • 92
  • Ah, nice find! Armed with this information I found [this relevant class](https://github.com/JetBrains/kotlin/blob/v1.1.2/core/descriptor.loader.java/src/org/jetbrains/kotlin/platform/JavaToKotlinClassMap.java) from within the Kotlin repo, which defines the mappings described in the documentation. In fact the whole [`platform` directory](https://github.com/JetBrains/kotlin/tree/v1.1.2/core/descriptor.loader.java/src/org/jetbrains/kotlin/platform) is interesting. – stkent Jun 28 '17 at 00:39
  • Also [the `Converter` type](https://github.com/JetBrains/kotlin/blob/v1.1.2/j2k/src/org/jetbrains/kotlin/j2k/Converter.kt). – stkent Jun 28 '17 at 00:41