简体   繁体   中英

Scala: Declaring method with generic type parameter

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.

  • 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") 
  • II. Another, more involved way, is to externalize implementation of readValue to some user-provided object (type class):

     trait ValueReader[T] { def readValue(s: String): T } def readValue[T: ValueReader](s: String): T = { val reader = implicitly[ValueReader[T]] reader.readValue(s) } implicit val doubleReader = new ValueReader[Double] { def readValue(s:String) = // implementation for Double } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM