Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Declaring method with generic type parameter

Tags:

generics

scala

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.

like image 573
Neil Avatar asked Sep 07 '13 19:09

Neil


People also ask

How do I use generic in Scala?

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.

How do you invoke a generic method?

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.

What is the meaning of => in Scala?

=> 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 .

What do you call a Scala method that is parameterized by type as well as by value?

Language. Methods in Scala can be parameterized by type as well as by value. The syntax is similar to that of generic classes.


1 Answers

  • 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")
    
like image 52
Arseniy Zhizhelev Avatar answered Sep 25 '22 01:09

Arseniy Zhizhelev