What is the equivalent of the following Java method declaration in Scala:
public <T> T readValue(java.lang.String s, java.lang.Class<T> tClass)
In other words, I'd like to declare a method that takes a class of type T, and returns an instance of that type.
Defining a generic classGeneric classes take a type as a parameter within square brackets [] . One convention is to use the letter A as type parameter identifier, though any parameter name may be used. This implementation of a Stack class takes any type A as a parameter.
To call a generic method, you need to provide types that will be used during the method invocation. Those types can be passed as an instance of NType objects initialized with particular . NET types.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
Language. Methods in Scala can be parameterized by type as well as by value. The syntax is similar to that of generic classes.
I. Very close to what you want:
def readValue[T:ClassTag](s:String):T = {
val tClass = implicitly[ClassTag[T]].runtimeClass
//implementation for different classes.
}
usage is a bit clearer than in Java:
val myDouble = readValue[Double]("1.0")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With