Working on scala traits and getting an error


#1

Hi Everyone,

I have started learning scala and am working on a task and facing some problem:

Following is what I have worked on. But I am not getting a desired output but an error. " class Variables need to be abstract since it has two unimplemented variables"

Need your Help. Thanks in Advance.

trait ArithmeticOperations {

var x :Int
var y: Int

def add
def subtract
def multiply
def divide

}

class Variables (xc:Int, yc:Int) extends ArithmeticOperations {

x= xc
y= yc

def add() = x + y
def subtract() = x - y
def multiply() = x * y
def divide() = x / y

}

object TraitExample extends App{
val input1 = args(0).toInt
val input2 = args(1).toInt
var variable = new Variables(input1, input2)
println(variable.add())
println(variable.subtract())
println(variable.multiply())
println(variable.divide())
}

Output:

Execute the program to print the outputs:
(Traits.scala is a file name)

scala Traits.scala 5 3

Output will be:
8
2
15
1


#2

I made a mistake not to initialize the x and y variable. I have corrected that but still I am not getting the desired output.
I am getting
()
()
()
()

with the call I have made in the code.


#3

You didn’t declare the return types of the defs in your trait, so they default to type Unit. (Which always prints as ().)


#4

Greetings dear professional Colleagues,

Please, I am very new in Scala. I want to learn from you how I can set eclipse environment to be scala EDI.

Your help is much appreciated.

Folakemi


#5

You’re looking for the Scala IDE. But note that not an awful lot of people are using it nowadays – most folks are currently using IntelliJ.


#6

Thanks for your response. It work :slight_smile: