Question
Answer and Explanation
To print the working directory in Scala, you can use the System.getProperty("user.dir")
method. This method retrieves the value of the system property named "user.dir", which represents the current working directory of the Java Virtual Machine (JVM) where your Scala code is running.
Here's how you can do it:
object WorkingDirectoryPrinter {
def main(args: Array[String]): Unit = {
val workingDir = System.getProperty("user.dir")
println(s"The current working directory is: $workingDir")
}
}
Explanation:
1. `object WorkingDirectoryPrinter`: This defines a Scala singleton object, which is a class with only one instance. It's a common way to define the entry point of a Scala application.
2. `def main(args: Array[String]): Unit`: This is the main method, the entry point of the application. It takes an array of strings as command-line arguments (though we're not using them here) and returns `Unit` (similar to `void` in Java).
3. `val workingDir = System.getProperty("user.dir")`: This line retrieves the value of the "user.dir" system property using the `System.getProperty()` method and assigns it to the immutable variable `workingDir`.
4. `println(s"The current working directory is: $workingDir")`: This line prints the working directory to the console. The `s` before the string indicates an interpolated string, allowing you to embed the value of the `workingDir` variable directly into the string.
How to Run:
1. Save the code in a file named `WorkingDirectoryPrinter.scala`.
2. Compile the code using the Scala compiler: `scalac WorkingDirectoryPrinter.scala`
3. Run the compiled code: `scala WorkingDirectoryPrinter`
The output will display the current working directory from where you executed the `scala` command.
This approach is straightforward and reliable for obtaining the working directory in Scala applications.