Dynamically create case class

前端 未结 3 1732
北恋
北恋 2020-12-10 22:24

I am using a csv library that takes a case class and turns it into rows for me to read.

The syntax is pretty close to File(path).asCsvReader[caseClass].

3条回答
  •  自闭症患者
    2020-12-10 23:02

    So basically you need a runtime information about your case class? I guess you should use ClassTag:

    import scala.reflect._
    
    def asCsvReader[T: ClassTag]: T = {
      classTag[T].runtimeClass.getDeclaredConstructor(...).newInstance(...)
      ...
    }
    

    This will allow you to instantiate your case class at runtime.

    Since you can figure out the types of your CSV columns you can provide the appropriate types into getDeclaredConstructor and newInstance methods.

提交回复
热议问题