Search code examples
scalaclassobjectcallsend

Apply to value to class inside def and send it to another val at another class


Hope you are doing good, I just started a basic scala programming for creating API. So I have models product with the following code:

import.blablabla._
case class Product(prodId:Int, prodBig:int, prodPcs:Int, price:Int, resProd:Double)

object Product{
  def add(prodId:Int, prodBig:int, prodPcs:Int): Product = {
    Storage.cnts(prodBig, prodPcs)
    var resProd = ?????????
    val price = 4000
    val resJsn = Product(clientId, prodBig, prodPcs, price, resProd)
    Ok(Json.obj("result" -> resJsn)).withHeaders(
              AUTHORIZATION -> endtoken)
      }

and other class with the following code:

import.blablabla._
case class Storage (resProd: Double)    

    object Storage {
          def cnts(prodBig:Int, prodPcs:Int) {
            val prod = prodPcs/prodBig
            ??????????
          }
        }

My Question is: How do I apply value of prod to resProd? and how do I apply the Storage (resProd) value to resProd at Product class?

I believe this could be easy to answer if you had experience with java or scala. Thanks :)


Solution

  • If you want to manually update Storage.resProd by calling cnts, I don't think it's a good idea. Companion object, object Storage in your code, is suitable for factory methods.

    So I recommend
    1. Create new Stroage in cnts:

    def cnts(prodBig:Int, prodPcs:Int) {
        val prod = prodPcs/prodBig
        new Storage(prod)
    }
    

    2. Move cnts to class Storage:

    case class Storage (var resProd: Double) {
       // some update method comes here
    }