logo
down
shadow

Scala: create instance by type parameter


Scala: create instance by type parameter

By : Moises Ferreira
Date : October 18 2020, 03:08 PM
Hope that helps I am trying to create a generic method to create class instance by specified type parameter. , You can do this:
code :
import scala.reflect.ClassTag

def executor[T <: P](cfg: String)(implicit tag: ClassTag[T]): Unit  = {
  tag.runtimeClass.getConstructor(classOf[String]).
    newInstance(cfg).asInstanceOf[T].run()
}
executor[P1]("someCfg")
executor[P2]("someCfg")
executor[P3]("someCfg")


Share : facebook icon twitter icon
How to instantiate an instance of type represented by type parameter in Scala

How to instantiate an instance of type represented by type parameter in Scala


By : tcherif
Date : March 29 2020, 07:55 AM
it fixes the issue EDIT - apologies, I only just noticed your first error. There is no way of instantiating a T at runtime because the type information is lost when your program is compiled (via type erasure)
You will have to pass in some factory to achieve the construction:
code :
class BalanceActor[T <: Actor](val fac: () => T) extends Actor {
  val workers: Int = 10

  private lazy val actors = new Array[T](workers)

  override def start() = {
    for (i <- 0 to (workers - 1)) {
      actors(i) = fac() //use the factory method to instantiate a T
      actors(i).start
    }
    super.start()
  }
} 
val ba = new BalanceActor[CalcActor]( { () => new CalcActor } )
ba.start
val size = 10
0 until size //is equivalent to:
0 to (size -1)
Create an instance of a class from an instance of the type of its generic parameter

Create an instance of a class from an instance of the type of its generic parameter


By : NeonVibe
Date : March 29 2020, 07:55 AM
I hope this helps . I want to do this: , You can use a custom implicit operator, e.g:
code :
public static implicit operator ValueContainer<T>(T value) {
    return new ValueContainer { Value = value };
}
How to create instance with type parameter through scala reflection?

How to create instance with type parameter through scala reflection?


By : irintch3
Date : March 29 2020, 07:55 AM
I wish this help you Here is my code , The following code with Int doesn't throw exception
code :
val word2vec = Class.forName("b2.Word2Vec").newInstance().asInstanceOf[Algorithm[Int]]
val a = word2vec.someMethod(123)
println(a) // 123
val word2vec = Class.forName("b2.Word2Vec").newInstance().asInstanceOf[Algorithm[_]]
val a = word2vec.someMethod(123)
println(a) // 123
import scala.reflect.runtime.universe._
val mirror = runtimeMirror(this.getClass.getClassLoader)
val classSymbol = mirror.staticClass("b2.Word2Vec") // class Word2Vec
// if string is "int"
internal.typeRef(NoPrefix, classSymbol, List(typeOf[Int])) // Word2Vec[Int]
// if string is "float"
internal.typeRef(NoPrefix, classSymbol, List(typeOf[Float])) // Word2Vec[Float]
Creating an instance from a type parameter in scala

Creating an instance from a type parameter in scala


By : Aymen
Date : March 29 2020, 07:55 AM
will be helpful for those in need How about putting a factory method on BinExpr so that each subclass knows how to instantiate itself, given two new parameters. Here's a simplified example:
Can I extract the subclass instance of an abstract class from a Type parameter in Scala?

Can I extract the subclass instance of an abstract class from a Type parameter in Scala?


By : ArtemD
Date : September 22 2020, 09:00 PM
should help you out There is no way to convince the compiler that given the type of A it should infer the type of B.
Maybe if you expand a little bit more on your use case there could be another way using typecñasses.
code :
class C[T <: A, U](val b: U)
                  (implicit ev: U <:< B[T])
Related Posts Related Posts :
  • Why can't concrete members be overridden with abstract ones in scala?
  • String + StringOps = functor?
  • Akka remote: is it possible to work with classes from two differents app which don't have the same package name?
  • How to perform merge operation on spark Dataframe?
  • Converting command line argument key=value pair to Map in scala
  • Implement Actor model without Akka in Scala
  • calling reduce on list of akka http routes yields compilation error (no implicit value for parameter join)
  • Append/concatenate two RDDs of type Set in Apache Spark
  • Left to right arguments type inference
  • Gatling. ConnectException: connection timed out:
  • convert scala.collection.Iterator to java list
  • Is there a way I can get the Gatling "Report ID"?
  • class needs to be abstract since method in trait is not defined error
  • How to mock or stub AWS SDK S3 bucket calls in Scala or Java?
  • Multipart Form Errors with Lagom
  • Possible ways to check if a value exists in a sequence scala
  • How convert Spark dataframe column from Array[Int] to linalg.Vector?
  • What is the best way to write Scala codes for "if else" logic?
  • spark flatten records using a key column
  • Does it make sense to write a UDAF to perform a rolling regression on a spark dataframe?
  • Spark Scala: Count Consecutive Months
  • How to use fixture-context objects with async specs in ScalaTest?
  • Problems with Source.fromURL when trying to close it in finally block
  • Scala: custom grammar/parser combinators
  • Convert a groupByKey to reduceByKey
  • Displaying output under a certain format
  • How to write a nested query?
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com