0

I'm looking for a generic way of array creation in Scala.js.

The following code works fine in JVM and Scala Native platforms:

def newArray[A](fqcn: String, size: Int): Array[A] = {
  val clazz = Class.forName(fqcn)
  java.lang.reflect.Array.newInstance(clazz, size).asInstanceOf[Array[A]]
}

But in Scala.js I cannot find an ability to create an instance of java.lang.Class.

I've tried such replacement for Class.forName but it doesn't work for arbitrary classes:

val clazz = scala.scalajs.reflect.Reflect.lookupInstantiatableClass(fqcn)
  .getOrElse(throw new ClassNotFoundException(fqcn))
  .runtimeClass
1
  • 1
    Can you just use ClassTag[A].newArray? Commented Jul 2 at 14:57

1 Answer 1

3

You cannot get a java.lang.Class from a string. There's the reflection API, as you noticed, but that is only for very specific classes that have been annotated with @EnableReflectiveInstantiation. This is usually only used by test framework classes.

The Scala way would be to take an implicit ClassTag[A], which is the defining purpose of ClassTag. An alternative is to pass the java.lang.Class as argument, and at call site, give it as a classOf[C] for a concrete C.

From a string, it's not possible.

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.