Object creation and function calling ambiguity issue


I am newbie to this Language. I have a general query regarding object creation of a class whose name is lets say Person and we have a function in the main class with the same name as that of class i.e Person. When we try to create a object of Person class by Person(), how compiler differentiate between a function calling and object creation?


It doesn’t. The function and the constructor of the class are considered to be overloads, just as if they were two methods in the same class with the same name. If they have the same parameter types, the compiler will report an overload resolution error when you try to call the method. If they have different parameter types, thi compiler will choose the method to call based on the parameter type.


But function is in different class( not in the class Person, but in the class where main method resides) in that case it is not overloaded


This doesn’t matter. The compiler treats these declarations as overloads.


Thanks @yole


Even if the function and the class constructor can look like the same overloads, one of them can be preferred, if it’s more local to the caller’s scope. For example if Person class is declared on top-level and Person function is inside some other class. then inside that class the function will be considered shadowing that class constructor:

class Person(val name: String = "")

class Test {
    fun Person() = Person(name = "foo")
    init {
        println(Person().name) // prints foo