1

I have an Array of String: EmpArray = Array(emp_id,emp_name,city)

Instead of manually creating case class (say -- case Class Emp (val emp_id: String, val emp_name:String, val city:String)

can I create a case class from the Array itself

case class Emp (EmpArray(0), EmpArray(1), EmpArray(2)) -- //hypothetical

can anything of such sort possible in scala?

2
  • 1
    You might want to take a look at this. Commented Dec 21, 2018 at 20:15
  • I don't know how that post is answering my question above Commented Dec 21, 2018 at 20:20

1 Answer 1

1

If you really have to, you can do it with runtime compilation:

import scala.reflect.runtime.universe
import scala.tools.reflect.ToolBox

def compileCaseClass(name: String, values: (String, String)*): Class[_] = {
  val tb = universe.runtimeMirror(getClass.getClassLoader).mkToolBox()
  val code = s"""
    |case class $name(${values.map{case (n, t) => n + ": " + t}.mkString(",")})
    |scala.reflect.classTag[$name].runtimeClass
  """.stripMargin
  println(code)
  tb.compile(tb.parse(code))().asInstanceOf[Class[_]]
}

Usage example:

val arr = Array("emp_id", "emp_name", "city")
val types = Array.fill(3){"String"}
val emp = compileCaseClass("Emp", (arr zip types): _*)
val inst = emp.getConstructors.head.newInstance("foo", "bar", "baz")
println(inst)

it indeed outputs the usual toString of a case-class instance:

Emp(foo,bar,baz)

Note that it requires the reflection / compiler toolbox as dependency: it's there if you are running it in the REPL or as a script, but in ordinary projects, you have to add it as separate dependency.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.