Compiler gives of an error scala> import scala." /> Compiler gives of an error scala> import scala." /> Compiler gives of an error scala> import scala."/>

How to produce integer literal as an attribute in Scala XML output?

1.2k Views Asked by At

I expect the following code to produce XML value with the following content:

<TestInteger value="10"/>

Compiler gives of an error

scala> import scala.xml._
import scala.xml._
scala> val x:Int = 10
x: Int = 10
scala> <TestInteger value={x}/>
<console>:8: error: overloaded method constructor UnprefixedAttribute with alternatives (String,Option[Seq[scala.xml.Node]],scala.xml.MetaData)scala.xml.UnprefixedAttribute <and> (String,String,scala.xml.MetaData)scala.xml.UnprefixedAttribute <and> (String,Seq[scala.xml.Node],scala.xml.MetaData)scala.xml.UnprefixedAttribute cannot be applied to (java.lang.String,Int,scala.xml.MetaData)
       <TestInteger value={x}/>

What am I doing wrong? Are integer literals allowed in XML?

I'm using Scala 2.7.7

2

There are 2 best solutions below

1
Nikolay Ivanov On BEST ANSWER

Look like your XML is violating XML specification according to this each attribute value must begin with a double quote. See AttValue rule.
Edit:
After some googling around it seems that scala.xml.UnprefixedAttribute has Constructor that only supports strings as values so since there is no build-in implicit conversion from Int's to String this code of yours will not work same as code :

val a : String = 10

Scala doesn't now how convert integers to strings automatically but following code however will work

implicit def intToString(i:Int) = i.toString  
val a : Int = 10
val b  = <Test attr={a}/>
5
Daniel C. Sobral On

Scala XML has no support for any type other than String. One can extend the library to add alternatives to Text, but, as it is, there's no support.