Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there constructor references in Kotlin?

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.

like image 682
Kirill Rakhman Avatar asked Sep 25 '22 22:09

Kirill Rakhman


People also ask

Are there constructors in Kotlin?

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.

Can Kotlin object have constructor?

In Kotlin, a class can have a primary constructor and one or more additional secondary constructors.

What are constructor references?

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.

What is true about Kotlin constructors?

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.


1 Answers

You can get a function instance for a constructor by simply using ::ClassName, as if it were a factory function.

like image 209
Ilya Ryzhenkov Avatar answered Oct 18 '22 18:10

Ilya Ryzhenkov