Thursday, October 4, 2018

Why Kotlin does not use new keyword when creating a new instance?

The answer is

1) Kotlin functions are first-class
2) A constructor is a function that can be assigned to a property of a function type, passed as an argument to a higher-order function or returned by a higher-order function.

class Foo
val foo : () -> Foo = ::Foo
val a : Foo = foo() // Creating a Foo through a property 
val b : Foo = Foo() // Creating a Foo directly by calling a 
                    // constructor
val c : Foo = new Foo() // <-- Incorrect syntax that clearly shows
                        // that "new" keyword has no place in 
                        // a language where functions 
                        // are first-class

No comments:

Post a Comment