Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8084041
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T17:40:13+00:00 2026-06-05T17:40:13+00:00

Here is the code I have written for Rectangle class. class Rectangle (l: Double,

  • 0

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:

  1. Given the length and width calculate the area of the Rectangle
  2. Given the length and area calculate the width of the Rectangle
  3. Given the width and area calculate the length of the Rectangle
  4. 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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T17:40:15+00:00Added an answer on June 5, 2026 at 5:40 pm

    Here is an example for you:

    case class Rectangle(length: Double, width: Double) {
        require (length > 0, width > 0)
    
        lazy val area = length * width
        override def toString = s"length: $length, width: $width, area: $area"
    }
    
    object Rectangle {
        def fromLength(length: Double) = Rectangle(length, length)
        def fromLengthArea(length: Double, area: Double) = Rectangle(length, area / length)
        def fromWidthArea(width: Double, area: Double) = Rectangle(area / width, width)
        def show(rect: Rectangle) = println(rect)
    }
    
    // Usage
    
    Rectangle show Rectangle(2, 3)
    Rectangle show Rectangle.fromLength(2)
    Rectangle show Rectangle.fromLengthArea(2, 6)
    Rectangle show Rectangle.fromWidthArea(3, 6)
    

    I can recommend you to always case classes where it’s appropriate, especially for classes like Rectangle.

    show method 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 of Rectangle can be considered not referentialy transparent because you are using require. You can avoid this by insuring, that Rectangle will always receive correct values somewhere outside the class, but you also need to return something, when Rectangle class cannot be created because of validation errors. You can use Option class for this purpose. Here is little example of this:

    case class Rectangle private (length: Double, width: Double) {
        lazy val area = length * width
        override def toString = s"length: $length, width: $width, area: $area"
    }
    
    object Rectangle {
        def fromLengthWidth(length: Double, width: Double) = 
            validating(length, width)(new Rectangle(length, width))
    
        def fromLength(length: Double) = validating(length)  {
            new Rectangle(length, length)
        }
    
        def fromLengthArea(length: Double, area: Double) = validating(length, area) {
            new Rectangle(length, area / length)
        }
    
        def fromWidthArea(width: Double, area: Double) = validating(width, area) {
            new Rectangle(area / width, width)
        }
    
        def show(rect: Option[Rectangle]) = println(rect getOrElse "Invalid Rectangle!!!")
    
        private def validating[R](values: Double*)(fn: => R) = 
            if (values forall (_ > 0)) Some(fn)
            else None   
    }
    
    Rectangle show Rectangle.fromLengthWidth(2, 3)
    Rectangle show Rectangle.fromLength(0)
    
    // prints:
    //    length: 2.0, width: 3.0, area: 6.0
    //    Invalid Rectangle!!!
    

    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 None object which is instance and subclass of Option class).

    I added area method to the class, but you can of course write an independent method or function that calculates area:

    def area(rect: Rectangle) = rect.length * rect.width
    

    or

    val area = (rect: Rectangle) => rect.length * rect.width
    

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Here is the code I have written: super(Add contact); setLayout(new FlowLayout()); IPAddress = new
I have this code here, which is intended to allow any type of arguments:
I have this code here, {foreach from=$cart.cartItems item=item name=cart} <div id=cart2Produkt> <p>{if $item.Product.ID} <a
Here is the code I have written which splits a string in c and
here is the code I have written in java I think it is right.
Here is my code I have written thus far, along with the errors I'm
Here is the code I have written a server and client. But when i
JAVA Code Here is some part of my code that I have written in
Here is the code I have written, It should fetch the first entry in
Here is the code I have written: function p_deal(id) { var card1_val = Math.floor(Math.random()

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.