square / kotlinpoet

A Kotlin API for generating .kt source files.
https://square.github.io/kotlinpoet/
Apache License 2.0
3.87k stars 285 forks source link

Using kotlin mutable collections for typenames #279

Open AlecKazakova opened 6 years ago

AlecKazakova commented 6 years ago

If I do

MutableList::class.asTypeName()

the generated code uses kotlin.collections.List

I have worked around with ClassName("kotlin.collections", "MutableList")

swankjesse commented 6 years ago

This might be a problem with Kotlin itself.

assertThat(MutableList::class.qualifiedName).isEqualTo("kotlin.collections.MutableList")
org.junit.ComparisonFailure: 
Expected :kotlin.collections.MutableList
Actual   :kotlin.collections.List
swankjesse commented 6 years ago

... looks like MutableList is completely erased at compile-time.

assertThat(MutableList::class).isEqualTo(List::class)
AlecKazakova commented 6 years ago

should this be something kotlinpoet addresses then? List::class.asMutableTypeName() or better to just leave it as the manual ClassName usage

given your findings its probably impossible to have something thats safe at compile time

swankjesse commented 6 years ago

asMutableTypeName() is an interesting idea!

afollestad commented 5 years ago

Yeah something like...

fun KClass<*>.asMutableTypeName(): ClassName {
  return when (this) {
    List::class -> MUTABLE_LIST
    Map::class -> MUTABLE_MAP
    Set::class -> MUTABLE_SET
    else -> asTypeName()
  }
}

...is handy

Egorand commented 5 years ago

@afollestad btw we've introduced a large number of constants for frequently used ClassNames:

fun KClass<*>.asMutableTypeName(): ClassName {
  return when (this) {
    List::class -> MUTABLE_LIST
    Map::class -> MUTABLE_MAP
    Set::class -> MUTABLE_SET
    else -> asTypeName()
  }
}
ZacSweers commented 5 years ago

This, annoyingly, isn't covered by the new typeOf() API either :/

@Test
fun typeNameOf_mutable() {
  val type = typeNameOf<MutableList<String>>()
  assertThat(type.toString()).isEqualTo("kotlin.collections.MutableList<kotlin.String>")
}

yields

expected: kotlin.collections.MutableList<kotlin.String>
but was : kotlin.collections.List<kotlin.String>
ZacSweers commented 4 years ago

This is filed now https://youtrack.jetbrains.com/issue/KT-35877

seelikes commented 1 year ago

facing the same problem, no way to create a property with MutableList type, please help

Dutch-0 commented 1 year ago

facing the same problem, no way to create a property with MutableList type, please help

Did you actually read the issue?

I have worked around with ClassName("kotlin.collections", "MutableList")