toString type cast not accepted when arguments are passed to companion object


#1

Sir,

I am typing following in paste mode and it is being accepted but when I pass arguments for custid and orderid as strings it is not accepted. Will you please let me know where I am going wrong.Thanks in advance.

class order(var custid: Int,var orderid: Int,var orderdate: String,var orderstatus: String) {
  override def toString="order("+custid+','+orderid+','+orderdate+','+orderstatus+")"
}

object order {
   def apply(custid: Int,orderid: Int,orderdate: String,orderstatus: String):order = {
                 new order(custid,orderid,orderdate,orderstatus)
   }

   def apply(custid: String,orderid: String,orderdate: String,orderstatus: String):order={
               new order(custid.toInt,orderid.toInt,orderdate,orderstatus)
   }
}

scala> var o6=new order("1","2","8/8/18","zxcx")
:13: error: type mismatch;
found : String(“1”)
required: Int
var o6=new order(“1”,“2”,“8/8/18”,“zxcx”)


#2

@dgadiraju
When you are using the Singleton object and declaring the apply method you should not use the ‘new’ keyword rather you can create object by using this syntax which would call you apply method
var o6=order(“1”,“2”,“8/8/18”,“zxcx”)

I have tried the above syntax on my terminal and it worked.
Tell me if that helps.
Thanks