Home > OS >  Wrong usage of Classtag in Scala?
Wrong usage of Classtag in Scala?

Time:12-28

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.

CodePudding user response:

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] { ... }
  • Related