Kotlin / KEEP

Kotlin Evolution and Enhancement Process
Apache License 2.0
3.3k stars 356 forks source link

Primary constructor incompatibilities #281

Closed uinnn closed 1 year ago

uinnn commented 2 years ago

When you is creating a class thats maybe can have more than one constructor, sometimes runs in a little problem:

// error: "Supertype initialization is impossible without primary constructor"
class Example<K, V> : TreeMap<K, V>() {
  constructor() : super()
  constructor(comparator: Comparator<in K>?) : super(comparator)
  constructor(m: MutableMap<out K, out V>?) : super(m)
  constructor(m: SortedMap<K, out V>?) : super(m)
}

So if i put a primary constructor:

class Example<K, V>() : TreeMap<K, V>() {
  constructor(comparator: Comparator<in K>?) : super(comparator) // error: "Primary constructor expected"
  constructor(m: MutableMap<out K, out V>?) : super(m) // error: "Primary constructor expected"
  constructor(m: SortedMap<K, out V>?) : super(m) // error: "Primary constructor expected"
}

So, how i can create all constructors without no errors? A little fix for this example to add all compatibility with already implemented constructors:

class Example<K, V>(comparator: Comparator<in K>?) : TreeMap<K, V>(comparator) {
  constructor(map: MutableMap<K, V>) : this(null) {
     putAll(map)
  }
}

I suggest add a compatibility to add the super() without needing a obrigatory primary constructor call with this() like:

class Example<K, V>(comparator: Comparator<in K>?) : TreeMap<K, V>(comparator) {
  constructor(m: MutableMap<out K, out V>?) : super(m) // no error
}
JakeWharton commented 2 years ago

This is not a KEEP. For questions try StackOverflow or the Kotlin chat. For bugs please use http://kotl.in/issue.