【问题标题】:it is possible to cast to wrong types without exception in scala在scala中可以毫无例外地转换为错误的类型
【发布时间】:2016-04-04 23:15:58
【问题描述】:

前几天我写了一个代码来过滤列表中的混合行为。

她是一个示例代码,应该描述我遇到的问题。

def myFilter[A](toFilter : Any) : Option[A] = toFilter match {
  case keep : A => Some(keep)
  case _ => None
}

// what happens
myFilter[Int]("hallo") // => Option[Int] = Some(hallo)

// what I expect
myFilter[Int]("hallo") // => Option[Int] = None
myFilter[Int](1) // => Option[Int] = Some(1)

也许我做错了什么,但它给我带来了很多问题,我现在必须创建很多代码,我希望通过这个函数使代码更具可读性。

【问题讨论】:

  • 尝试访问值时会抛出异常,查看thisthis
  • 这很好,但遗憾的是它并没有解决我的问题:(

标签: scala erasure


【解决方案1】:

只需提供ClassTag

scala> import scala.reflect.ClassTag
import scala.reflect.ClassTag

scala>   def myFilter[A: ClassTag](toFilter : Any) : Option[A] = toFilter match {
     |     case keep : A => Some(keep)
     |     case _ => None
     |   }
myFilter: [A](toFilter: Any)(implicit evidence$1: scala.reflect.ClassTag[A])Option[A]

scala> myFilter[Int]("hallo")
res2: Option[Int] = None

scala> myFilter[String]("hallo")
res3: Option[String] = Some(hallo)

【讨论】:

  • 把class标签直接加到type参数上的有趣记法
【解决方案2】:

类型因类型擦除而消失。但是,您可以提供类型,尝试类似

def myFilter[A](toFilter : Any)(implicit classTag: ClassTag[A]) : Option[A] = toFilter match {
  case keep : A => Some(keep)
  case _ => None
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 2017-04-17
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    相关资源
    最近更新 更多