Scala - 伴侣对象&适用:不可理解的错误

时间:2014-01-31 17:05:39

标签: xml scala companion-object

我无法使用配套对象创建表示XML解析文档的类。

以下是该类的代码:

package models

import javax.xml.bind.Element
import scala.xml.Elem
import javax.xml.validation.SchemaFactory
import javax.xml.transform.stream.StreamSource


trait MyXML {

case class ElémentXML(code_xml: scala.xml.Elem) {

def validate: Boolean = {

try ({
  val schemaLang = "http://www.w3.org/2001/XMLSchema"
  val factory = SchemaFactory.newInstance(schemaLang)
  val schema = factory.newSchema(new StreamSource("Sites_types_libelles.xsd"))
  val validator = schema.newValidator()
  validator.validate(new StreamSource(code_xml.toString))
  true
}) catch {
  case t:Throwable => false
}
}



}

object ElémentXML {

def apply(fichier: String) {

  try{
  val xml_chargé = xml.XML.loadFile(fichier)
  Some(new ElémentXML(xml_chargé))
  }catch{
    case e:Throwable => None
  }
}
}

}

以下是使用此类的应用程序代码:

val xml1:ElémentXML = ElémentXML("app/models/exemple_bon.xml")
xml1 must not beEqualTo(None)

错误是:

type mismatch; found : String("app/models/exemple_bon.xml") required: 
 scala.xml.Elem

我根本就不明白这个错误(以及我如何删除它)。

谢谢!

1 个答案:

答案 0 :(得分:5)

您的申请方法是一个程序。将其修改为apply(fichier: String): ElémentXML = ...

合成案例适用的重载由期望的类型解决。

这就是为什么不推荐使用过程语法的原因:

apm@mara:~/tmp$ scala -Xfuture -deprecation
Welcome to Scala version 2.11.0-20140129-135431-0e578e6931 (OpenJDK 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def f() { }
<console>:1: warning: Procedure syntax is deprecated. Convert procedure `f` to method by adding `: Unit =`.
       def f() { }
               ^
<console>:7: warning: Procedure syntax is deprecated. Convert procedure `f` to method by adding `: Unit =`.
       def f() { }
               ^
f: ()Unit

这样做的一个奇怪的影响是最后一行按值丢弃:

scala> :pa
// Entering paste mode (ctrl-D to finish)

case class C(c: Int)
object C {
def apply(s: String): Unit = C(s.toInt)
}

// Exiting paste mode, now interpreting.

defined class C
defined object C

scala> C(4)
res2: C = C(4)

scala> C("4")

scala> val x: C = C(4)
x: C = C(4)

scala> val x: C = C("4")
<console>:11: error: type mismatch;
 found   : String("4")
 required: Int
       val x: C = C("4")
                    ^

scala> val x: Unit = C("4")
x: Unit = ()

scala> val x: Unit = C(4)  // works silently
x: Unit = ()