Writing out a Scala class and problem here is that the compiler thinks that the code is a unit not returning the proper value. It’s a method used to set a property in the class:
def setObject(`object`:StripeObject):StripeObject = {
this.`object` = `object`
}
The error is: type mismatch; found : Unit required: com.stripe.StripeObject
The full class is:
case class EventData(var previousAttributes: HashMap[String,Object], var `object`:StripeObject) extends StripeObject {
def getPreviousAttributes = {
previousAttributes
}
def setPreviousAttributes(previousAttributes: HashMap[String, Object]) = {
this.previousAttributes = previousAttributes
}
def getObject = {
`object`
}
def setObject(`object`:StripeObject):StripeObject = {
this.`object` = `object`
}
}
How do I make sure it doesn’t return a Unit?
In Java setters are usually defined with
voidreturn type:The Scala equivalent is
Unit, which is also the value of an assignment expression. So in Scala you’d write a setter as one of the following (which are all equivalent, with the first being the most idiomatic):This is just a convention for setters, though, and you could easily return the value if you wanted:
This would be a bit unusual, but wouldn’t be likely to cause problems, even for callers who were expecting
Unit.