3

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

Basilevs
  • 22,440
  • 15
  • 57
  • 102

2 Answers2

3

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}/>
Nikolay Ivanov
  • 8,897
  • 3
  • 31
  • 34
  • Then again schema allows integer values nevertheless (I'll give up on quotes, but still want to treat an argument as integer. http://www.informit.com/library/content.aspx?b=STY_XML_21days&seqNum=71 – Basilevs Mar 05 '11 at 12:49
1

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.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • That is wrong. Scala XML does only support `String` values in attributes but supports any type for nodes! `{ 5 }` will compile. The integer literal `5` will be encapsuled in an `Atom[Int]`. That works for all types! – Martin Ring Mar 06 '11 at 20:15
  • @Martin Mmmmm. I thought `Atom` was abstract, the only subclasses being `Text`, `Unparsed` and `PCData`. – Daniel C. Sobral Mar 07 '11 at 04:29
  • Atom is not abstract (See [api](http://www.scala-lang.org/api/2.8.1/scala/xml/Atom.html)) . `scala> val xml = { 42 }` `xml: scala.xml.Elem = 42` `scala> xml.child(0).isInstanceOf[scala.xml.Atom[Int]]` `res0: Boolean = true` – Martin Ring Mar 07 '11 at 18:54
  • @Martin I noticed that after your comment, but I thought it wasn't before. By the way, `Int` there is not checked, as it is type erased. Yes, it is an `Atom`, but so would be a `Text`. – Daniel C. Sobral Mar 07 '11 at 19:48
  • You can still get the `Int` or any other object out of the `Atom` because it is stored in the `data` field of `Atom[T]`. So it is different from `Text(42.toString)` – Martin Ring Mar 07 '11 at 20:11