AZ_ AZ_ - 1 month ago 9
Scala Question

Scala class must be declared abstracting, if I use => instead of = why?

I am new to Scala and when I write a method with

=>
it gives the error that class must be abstract or override method and when I use
=
then it's ok Why?

class MainScala {
//change => to = then everything is ok. why?
def main1(args: Array[String]): Unit => {

}
}



enter image description here

Answer

In Scala, method name and its argument list(s) are followed by : and the type of return value. Then there is an optional part: = METHOD_BODY, where METHOD_BODY is simply the body of a method as a single statement or in a statement block (that is, surrounded by {}).

Example method definition then looks like this:

def foo(someArgument: TypeOfArgument): ReturnType = { 
  // some body that returns a value of ReturnType
}

Note that I said that part = { ... } is optional; if you omit that, method is just declared, but not defined. Its type signature is known (e.g. it's a method that takes a value of type TypeOfArgument and returns a value of type ReturnType) but no actual method body is provided (method is not implemented). If this is the case, method is considered to be abstract. Abstract methods can only be declared in traits and abstract classes. Classes that extend a trait or abstract class with an abstract method must implement that method.

In your case, method def main1(args: Array[String]): Unit => {} is a declaration of an abstract method (method without a body) that returns a value of type Unit => {}. My personal advice is that you don't pay much attention to what this type means because it doesn't make much sense anyway (I can tell you that => means that it's a function, so you have a function from Unit to {}; a rather weird function to be honest, and most likely not what you want).

On the other hand, method def main1(args: Array[String]): Unit = {} is a declaration of a method that returns value of type Unit (that is, it doesn't return anything; technically it returns value () which is an empty value, but we could say that methods that return Unit either don't do anything or perform some side effect because they don't return anything useful) and its body is simply an empty statement block {}. Note that if you define your method as an abstract method, you would need to do so in a trait or declare your class to be abstract, but you are in a (concrete) class, hence the error. If you define it by using =, however, means that you have fully implemented that method. To be honest, it's pretty useless since it's implemented with an empty body, but it's still implemented.

Comments