Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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] { ... }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading