Did you guys think about “copy-constructors” for d...
# language-proposals
n
Did you guys think about “copy-constructors” for data classes? 😉
1
b
Like this?
Copy code
data class Foo(bar: Bar, baz: Baz) {
	fun copy (bar: Bar = this.bar.copy(), baz: Baz = this.baz.copy()) = Foo(bar, baz) 
}
n
something like this, yeah but it be more like
Foo(foo: Foo) => foo.copy()
you pretty much create a new clone but instead of calling clone you use a copy constructor
(especially in the future, with value types, that would be cool :D)
b
ah, I see. As a much more generally powerful feature, I'd like to see "factory" constructors, which you can call like a normal constructor but don't behave like one. For instance:
Copy code
class Foo(bar: Bar) {
    private val shared = Foo(bar = Bar())
    
    factory constructor() = if (condition) shared else Foo(Bar())
n
I think you could do this with companion object, can’t you?
but I guess you want the opposite of https://kotlinlang.org/docs/reference/multi-declarations.html 😄
constructing declarations 🙂
b
Mostly I want to change
Foo.create()
to
Foo()
n
ohh ok, sorry took a moment 😄
m
b
@miha-x64 not me personally 😛
p
@benleggiero Then make it an operator fun called invoke
Copy code
data class Sample(val string  : String) {
  
  companion object{
    
    operator fun invoke() = if(Random().nextBoolean()) Sample("bob") else Sample("alice")
  }
}

fun whatever(){
  val sample = Sample()
}
😍 1
b
w-woah... I did not know this was possible. I'm gonna have to play with this.
😂 1