Ronald
Ronald

Reputation: 187

Wrong usage of Classtag in Scala?

import scala.reflect.ClassTag


class IntStorage {
  var variable: Int = 5
}


class testing[T : ClassTag] {
  var example = Array.ofDim[T](10, 10)
  def testFunc(): Int = example(0)(0).variable
}

Error: value variable is not a member of T

I do not understand why I get this error, even though I use a Classtag.

Upvotes: 0

Views: 177

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

The ClassTag is fine. But you declared testing to work for any class, not just IntStorage. What if I call new testing[String]()? String is a perfectly valid class with a class tag, but it doesn't have a variable field. I could call it with any class.

Is it possible you meant

class testing[T <: IntStorage : ClassTag] { ... }

Upvotes: 2

Related Questions