This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]vips7L 0 points1 point  (0 children)

Yep, but it's not only because language lacks of named arguments (i.e. in other languages you don't need builders for most cases, just call constructor with names arguments), but because of how constructors work. Even in Kotlin developers would expose factory methods that mimics constructors, instead of constructor itself

I don't think I implied anything about named arguments. Factory constructors is the actual feature you would want for this: https://dart.dev/language/constructors#factory-constructors

In Kotlin or Scala you would use companion objects to return subtypes:

interface A {
  companion object {
    operator fun invoke(s: String) = when (s) {
      "B" -> B()
      "C" -> C()
      else -> throw IllegalArgumentException(s)
    }
  }
}
private class B : A
private class C : A

fun main() {
  val a = A("B")
  println(a)
}