5

I am newbie to scala . I am trying to create an Object that extends abstract class like show below

object Conversions extends UnitConversions
{
 override def inchesToCentimeters(inches:Int) = inches * 2.5
 override def gallonsToLiters(gallons:Int) = gallons * 3.78
 override def milesToKilometers(miles:Int) = miles * 1.6
}

abstract class UnitConversions
{
 def inchesToCentimeters(inches:Int)
 def gallonsToLiters(gallons:Int)
 def milesToKilometers(miles:Int)
}

While i try to access the object's member functions i get () this expression as output .

Conversions.milesToKilometers(20) //I get output ()

More over is the below statement valid ???

var ucv:UnitConversions = new Conversions
println(ucv.milesToKilometers(3)) // I get output () here as well

Thanks in Advance !

pedrofurla
  • 12,763
  • 1
  • 38
  • 49
user3619698
  • 125
  • 3
  • 13

2 Answers2

9

You need to provide a return type for the functions, otherwise they return Unit:

abstract class UnitConversions {
  def inchesToCentimeters(inches:Int): Double
  def gallonsToLiters(gallons:Int): Double
  def milesToKilometers(miles:Int): Double
}
Jason Heo
  • 9,956
  • 2
  • 36
  • 64
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • How can I reconcile `You need to provide a return type for the functions` with: `abstract class F { def f = 42 }` , then: `(new F {}).f` returning: `res0: Int = 42` ` – Kevin Meredith Sep 21 '16 at 17:50
  • 2
    In that case, the return type is inferred from the implementation. If your abstract class does not provide a default implementation nor a return type, it is assumed to be a ``Unit`` function. – Jean Logeart Sep 21 '16 at 17:54
  • Thanks - `abstract class G { def g }`. Then, `class GImpl extends G { override def g: Int = 42 }` fails to compile: `error: overriding method g in class G of type => Unit;`. Any compiler flag or, I'm speculating, scala ticket to require a return type on such methods? – Kevin Meredith Sep 21 '16 at 17:58
  • 1
    The compiler flags are -Xfuture -deprecation (for warnings) and personally I love -Xfatal-warnings ;-) – Alexandru Nedelcu Sep 21 '16 at 19:31
  • THanks all .It helped – user3619698 Sep 22 '16 at 05:26
0

Regarding this question:

More over is the below statement valid ???

var ucv:UnitConversions = new Conversions println(ucv.milesToKilometers(3))

This doesn't compile. object basically means singleton and can be used for "static" methods. It doesn't make sense to create more than one instance of a singleton. Take a look at this question: Difference between object and class in scala

Community
  • 1
  • 1
corvus_192
  • 362
  • 4
  • 15