Scala- call a method of an object

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-10-10 04:09:41 Viewed : 255


In Scala, you can call a method of an object in the following way:

  1. Using the Object Name:

    You can call a method of an object by referencing the objects name followed by a dot (.) and the method name. If the method takes arguments, you include them within parentheses.

    Here is a basic example:

    scala
    object MyObject { def sayHello(name: String): Unit = { println(s"Hello, $name!") } } // Calling the method MyObject.sayHello("Alice")

    In this example, we call the sayHello method of the MyObject object and pass the argument "Alice" to it.

  2. Importing and Using the Object:

    If you have defined an object in a different package or file, you can import it and then call its methods directly without using the object name.

    scala
    // Import the object import com.example.MyObject // Call the method without the object name MyObject.sayHello("Bob")

    This approach is useful when working with objects defined in other parts of your codebase.

  3. Accessing the Objects Methods Within the Same Package:

    If you are working within the same package where the object is defined, you can call its methods directly without importing or referencing the object name.

    scala
    package com.example object MyObject { def sayHello(name: String): Unit = { println(s"Hello, $name!") } } // Calling the method without importing or using the object name MyObject.sayHello("Charlie")

    In this case, you can access the methods of MyObject without any additional steps.

These are the primary ways to call methods of an object in Scala. The choice of which method to use depends on whether the object is in the same package, in a different package, or if you want to access it without using the object name through import statements.

Search
Related Articles

Leave a Comment: