Scala methods
Scala Methods
In Scala, methods are defined using the def
keyword followed by the method name, parameter list, return type, and the method body. Here's an example of a Scala method:
def greet(name: String): Unit = {
println(s"Hello, $name!")
}
In this example, the method is named greet
and it takes a single parameter name
of type String
. The return type of the method is Unit
, which means it doesn't return any value. The method body consists of a single statement that prints a greeting message using the println
function.
To call a method in Scala, you simply use the method name followed by parentheses and the arguments, if any. For example:
greet("John")
This will call the greet
method with the argument "John"
, and it will print the message "Hello, John!".
Scala methods can have different return types, including Unit
(no return value), Int
, String
, or any other valid Scala type. The return type is specified after the parameter list using a colon (:
) followed by the type.
Methods can also have multiple parameters, and you can specify default values for parameters to make them optional. Additionally, you can use the return
keyword to explicitly return a value from a method, although it's not necessary in most cases.
I hope this explanation helps! Let me know if you have any further questions.