简体   繁体   English

Scala强制转换为选项[T]

[英]Scala cast Any to Option[T]

Something like: 就像是:

  def cast[T](o: Any): Option[T] = o match {
    case v: T => Some(v)
    case _ => None
  }

or: 要么:

  def cast[T](c: Class[T], o: Any): Option[T] = o match {
    case v: T => Some(v)
    case _ => None
  }

Is this a good idea? 这是一个好主意吗? Is there a standard library equivalent? 是否有标准库相当于?

Why do I get and how do I resolve the following Scala compiler warning: 为什么我会得到以及如何解决以下Scala编译器警告:

Warning:(7, 13) abstract type pattern T is unchecked since it is eliminated by erasure
    case v: T => Some(v)

Use class tag. 使用类标记。 Type information gets lost during runtime.So, you need provide type information which can be done using class tag. 在运行期间类型信息会丢失。因此,您需要提供可以使用类标记完成的类型信息。

import scala.reflect.ClassTag

def cast[T: ClassTag](o: Any): Option[T] = o match {
 case v: T => Some(v)
 case _ => None
}

Scala REPL Scala REPL

scala> cast[String]("hello")
res2: Option[String] = Some(hello)

scala> cast[Int]("scala")
res3: Option[Int] = None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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