Scala:使用泛型类型参数声明方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18677283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:38:16  来源:igfitidea点击:

Scala: Declaring method with generic type parameter

scalagenerics

提问by Neil

What is the equivalent of the following Java method declaration in Scala:

Scala 中以下 Java 方法声明的等效项是什么:

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.

换句话说,我想声明一个方法,它接受一个类型为 T 的类,并返回该类型的一个实例。

回答by Arseniy Zhizhelev

  • 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")
    
  • I. 非常接近你想要的:

    def readValue[T:ClassTag](s:String):T = {
      val tClass = implicitly[ClassTag[T]].runtimeClass
      //implementation for different classes.
    }
    

    用法比Java更清楚一点:

    val myDouble = readValue[Double]("1.0")
    

回答by Arseniy Zhizhelev

  • 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
    }
    
  • 二、另一种更复杂的方法是将 readValue 的实现外部化为一些用户提供的对象(类型类):

    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
    }