Here is the code I have written for Rectangle class.
class Rectangle (l: Double, w: Double) {
require (l > 0, w > 0)
val length = l
val width = w
def this (l: Double) = this (l, l)
def setDimensions (l: Double, w: Double) = new Rectangle (l, w)
def setLength (l: Double) = new Rectangle (l, width)
def setWidth (w: Double) = new Rectangle (length, w)
}
My question is how to write following functions (independent of Rectangle class) in Scala:
- Given the length and width calculate the area of the Rectangle
- Given the length and area calculate the width of the Rectangle
- Given the width and area calculate the length of the Rectangle
- Given the Rectangle Object show the length, width and area
This question arose after going through the following paragraph from this article:
Functional languages get their name from the concept that programs should behave like mathematical functions; in other words, given a set of inputs, a function should always return the same output. Not only does this mean that every function must return a value, but that functions must inherently carry no intrinsic state from one call to the next. This intrinsic notion of statelessness, carried over into the functional/object world to mean immutable objects by default, is a large part of why functional languages are being hailed as the great saviors of a madly concurrent world.
Please note that as Scala beginner, I am trying to grasp the FP part of it.
Here is an example for you:
I can recommend you to always case classes where it’s appropriate, especially for classes like
Rectangle.showmethod needs to print results, so you can’t avoid side-effects in this case. In other words this function is not referentialy transparent. Actually, the whole constructor ofRectanglecan be considered not referentialy transparent because you are usingrequire. You can avoid this by insuring, thatRectanglewill always receive correct values somewhere outside the class, but you also need to return something, whenRectangleclass cannot be created because of validation errors. You can useOptionclass for this purpose. Here is little example of this:As you can see I made constructor private and moved validation in the companion object (which can access private member of the class with the same name). So you can’t create invalid rectangle. But important point here, is that even if you provide broken length, you still receive something (in this case it’s
Noneobject which is instance and subclass ofOptionclass).I added
areamethod to the class, but you can of course write an independent method or function that calculates area:or
I hope this will help you in understanding this topic. If it’s still not clear (or my answer does not cover what you actually wanted to know), please don’t hesitate and leave a comment.