简体   繁体   中英

Types, Vector and Sealed Class Scala

I have the following code in a trait on SCALA,

trait example {
  type Schema = Vector[String] //Variable Names

  sealed abstract class Value;
  case class URI(name: Node) extends Value
  case class Literal(value: Node) extends Value
  case class BlankNode(name: Node) extends Value
  case class Variable(name: Node) extends Value

  type Fields = Vector[Value] //vector of values

Then, I am filling this objects using the element visitor from apache Jena in other class as follow:

class interpreter (q:Query) extends SPARQLInterpreter {
  //val Fields = Vector[Value]
  ElementWalker.walk(q.getQueryPattern(),

    new ElementVisitorBase() {

      override def visit(el: ElementPathBlock) {

        val triples: util.Iterator[TriplePath] = el.patternElts
        while (triples.hasNext()) {
          val aux1: Triple = triples.next().asTriple()
          val u:Value = URI(aux1.getSubject())
          val b:Value = BlankNode(aux1.getPredicate)
          val l:Value = Literal(aux1.getObject()) 
        }
      }
    })

Then, my question is how I should fill the Fields type declare on the trait, like Fields(u,b,l) because is a vector, but the compiler detects an error.

You can't write Fields(u,b,l) because there is no object Fields

What you could do is val fields: Fields = Vector(u, b, l) which creates a value names fields whose type is Vector[Value] and assigning something to it.

type is used to create a type alias which only affects the names of types. type Fields = Vector[Value] creates a new name for Vector[Value] and the types Fields and Vector[Value] can now be used interchangeably because they mean the same thing.

What this doesn't do is create a new name for the Vector object, so you can't refer to it using the name Fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM