Not like Swift because:
Extensions are allowed statically. Extensions do not actually change the classes that they extend. By defining extensions, you do not insert new members into the class, but simply make new functions called using the dot notation for type variables. ( Source )
If a companion object is defined in your target class, go with the s1m0nw1 approach. The advantage is that you can call the extension function without an instance of the (statically) target class.
If not , use the classic Factory pattern:
class Fruit(var name: String = "") { } class FruitFactory { companion object { fun create(name: String): Fruit { return Fruit().apply { this.name = "Tasty $name" } } } } fun main(args: Array<String>) { val orange = Fruit("Orange") println(orange.name) val apple = FruitFactory.create("Apple") println(apple.name) }
You can expand Factory as you wish with additional constructors, either nested or as extension functions.
Output:
Orange
Tasty apple
source share