scala> val count = 7
count: Int = 7
putting that into an XML attribute gives an error:
scala> val x = <element count={count}/>
<console>:8: error: overloaded method constructor UnprefixedAttribute with alternatives:
  (key: String,value: Option[Seq[scala.xml.Node]],next: scala.xml.MetaData)scala.xml.UnprefixedAttribute <and>
  (key: String,value: String,next: scala.xml.MetaData)scala.xml.UnprefixedAttribute <and>
  (key: String,value: Seq[scala.xml.Node],next1: scala.xml.MetaData)scala.xml.UnprefixedAttribute
 cannot be applied to (java.lang.String, Int, scala.xml.MetaData)
       val x = <element count={count}/>
                Inputs to XML attributes must be Strings. Integers and objects will not automatically be converted to Strings using their toString method. For example if you defined a Size class using a Units enum:
scala> object Units extends Enumeration {
     |   type Units = Value
     |   val COUNT = Value("count")
     |   val LB = Value("pounds")
     |   val OZ = Value("ounces")
     |   val GRAM = Value("grams")
     |   val KG = Value("kilograms")
     |   val GAL = Value("gallons")
     |   val QT = Value("quarts")
     |   val PINT = Value("pints")
     |   val FL_OZ = Value("fluid ounces")
     |   val L = Value("liters")
     | }
defined module Units
scala> class Size(val value: Double, val unit: Units.Units) {
     | override def toString = value + " " + unit.toString
     | }
defined class Size
created an instance of Size:
scala> val seven = new Size(7, Units.COUNT)
seven: Size = 7.0 count
then tried to put your size into an XML attribute, you would still get an error:
scala> val x = <element size={seven}/>
<console>:10: error: overloaded method constructor UnprefixedAttribute with alternatives:
  (key: String,value: Option[Seq[scala.xml.Node]],next: scala.xml.MetaData)scala.xml.UnprefixedAttribute <and>
  (key: String,value: String,next: scala.xml.MetaData)scala.xml.UnprefixedAttribute <and>
  (key: String,value: Seq[scala.xml.Node],next1: scala.xml.MetaData)scala.xml.UnprefixedAttribute
 cannot be applied to (java.lang.String, Size, scala.xml.MetaData)
       val x = <element size={seven}/>
                ^
You must explicitly call the toString method. This works:
scala> val x = <element count={count.toString} size={seven.toString}/>
x: scala.xml.Elem = <element size="7.0 count" count="7"></element>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With