相关疑难解决方法(0)

从方法返回泛型类型的实例

我想有一个方法getInstance,它接受一个字符串值并返回一个对象的实例,在方法签名中定义为泛型

  def getInstance[T](dataStr: String): Option[T] = {
      T match {
        case typeOf[String] => Some(dataStr)             // if type of T is String 
        case typeOf[Integer] => Some(dataStr.toInt)      // if type of T is Integer
        case typeOf[Boolean] => Some(dataStr.toBoolean)  // if type of T is Boolean
        case _ => throw new NoSuchElementException()
      }
  }
Run Code Online (Sandbox Code Playgroud)

如何在Scala中编写相同的内容?

Scala版本:2.11

scala

2
推荐指数
1
解决办法
48
查看次数

标签 统计

scala ×1