scala> class Rectangle (Length: Int, Width: Int) {; def getLlength (): Int = println (Length); def getWidth ():Int = println (Width); }
<console>:11: error: type mismatch;
found : Unit
required: Int
class Rectangle (Length: Int, Width: Int) {; def getLlength (): Int = println (Length:Int); def getWidth ():Int = println (Width:Int); }
^
<console>:11: error: type mismatch;
found : Unit
required: Int
class Rectangle (Length: Int, Width: Int) {; def getLlength (): Int = println (Length:Int); def getWidth ():Int = println (Width:Int); }
^
scala> class Rectangle (Length: Int, Width: Int) {; def getLlength (): Int = println
Share
I can tell you where you’re going wrong, but it’s not entirely obvious what it is you want to do here.
You’ve declared the
getLlength(sic) method to be returning a type ofInt. However, the body of this method is just aprintlncall, and so it will return the result of this call.printlnhas a return type ofUnit(since it returns nothing, and is executed only for its side effects).Hence your method is declared to return
Int, but you’ve implemented it in such a way that it’s return type would beUnit. Which is why you get a compile-time error.Do you want your method to return the length? If so, you should just return
Lengthrather than printing it. However, an even better way to do this is Scala would be to mark the constructor parameter as aval, which will automatically generate an accessor for it:Now anyone with a reference to e.g. a
Rectangle rectobject can callrect.Lengthto get the length. This is in fact the preferred way to access fields and field-like properties in Scala, rather than the getFoo convention that Java uses.If you really just want a “container” class that allows someone to access named parameters, consider case classes. You could define a functionally equivalent class as
This automatically generates accessor methods for both fields, sensible
toString(),equals()andhashCode()implementations – and you also get pattern matching as an added bonus.Any time you want a class which is mainly/entirely just a bundle of fields, case classes should be your starting point.
Note as well that variables in Scala are lowerCamelCase by convention. Declaring fields/constructor parameters with upperclass names (i.e.
Lengthinstead oflength) is surprisingly confusing for people reading your code, so you will do yourself and everyone else a favour by sticking to convention.