In Java we have the Class::new
syntax for constructor references. I know, there are callable references for methods, but how about constructors? A typical use case for me would be factories.
ConstructorsA class in Kotlin can have a primary constructor and one or more secondary constructors. The primary constructor is a part of the class header, and it goes after the class name and optional type parameters. The primary constructor cannot contain any code.
In Kotlin, a class can have a primary constructor and one or more additional secondary constructors.
Constructor Reference is used to refer to a constructor without instantiating the named class. The Constructor reference mechanism is yet another game changing addition by Java 8. You can pass references to constructors as arguments or assign to a target type.
In Kotlin, constructor is a block of code similar to method. Constructor is declared with the same name as the class followed by parenthesis '()'. Constructor is used to initialize the variables at the time of object creation.
You can get a function instance for a constructor by simply using ::ClassName
, as if it were a factory function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With