1

我有以下设置:

class Test[A](function: A => String) {
   def process(data: Any) {         //has to be Any since it is user IO
      if (data of Type A) 
          function(data)
   }
}

我似乎无法让类型检查工作。我尝试将隐式 TypeTag 添加到 Test[A] 但我无法从进程中访问它。是否可以在过程函数中匹配 Test 的类型参数?

4

3 回答 3

2

为此目的使用ClassTagand :match

import scala.reflect.ClassTag

class Test[A : ClassTag](function: A => String) {
  def process(data: Any) { //has to be Any since it is user IO 
    data match {
      case data: A => function(data)
      case _       =>
    }
  }
}

由于ClassTag范围的隐含,即使它是通用的,match也可以进行区分。A

于 2014-11-07T23:30:17.790 回答
0

我不确定为什么data必须是类型Any(用户输入不是类型String吗?),但如果确实如此,那么它可能反映了在编译时无法预期类型的​​情况。在这种情况下,您可能希望该方法在尝试强制转换时抛出运行时错误:

class Test[A](function: A => String) {
   def process(data: Any) = {
      function(data.asInstanceOf[A]) //might throw an error
   }
}

或者可能使用Try单子:

class Test[A](function: A => String) {
   def process(data: Any) = {
      Try(function(data.asInstanceOf[A]))
   }
}

当然,最可取的是data在编译时知道类型:

class Test[A](function: A => String) {
   def process(data: A) = {
      function(data)
   }
}
于 2014-11-07T23:18:31.663 回答
0

使用无形

  class Test[A: Typeable](function: A => String){
    import shapeless.syntax.typeable._
    def process(data: Any) {         //has to be Any since it is user IO
      data.cast[A] map { function(_) }
    }
  }

这个是安全的,因为它返回一个 Option[A],所以当转换失败时,您可以在 None 上进行模式匹配。

于 2014-11-07T22:45:18.373 回答