简体   繁体   English

Scala检查泛型的类型

[英]Scala check type of generics

How do I do something like this in Scala? 如何在Scala中执行此类操作?

case class Foo[A](x: A) {

  def get[T]: Option[T] = x match {
    case x: T => Some(x)    // if x is of type T i.e. T =:= A
    case _ => None
  }
}

val test = Foo("hi")
assert(test.get[Int] == None)
assert(test.get[String] == Some("hi"))

I tried this and ran into some weird time inference failure: 我尝试了这个,并遇到了一些奇怪的时间推断失败:

import scala.util.{Try, Success}
import reflect._

case class Foo[A](x: A) extends Dynamic {

  def get[T: ClassTag]: Option[T] = Try(x.asInstanceOf[T]) match {
    case Success(r) => Some(r) 
    case _ => None
  }
}

object Foo extends App {
  val test = Foo("hi")
  val wtf: Option[Int] = test.get[Int]
  assert(wtf.isInstanceOf[Option[String]])
  assert(wtf == Some("hi"))     // how????
  // val wtf2: Option[String] = wtf  // does not compile even if above assert passes!!
}

Surely a dupe, but hastily: 当然是一个骗局,但仓促:

scala> :pa
// Entering paste mode (ctrl-D to finish)

import reflect._
case class Foo[A](x: A) {

  def get[T: ClassTag]: Option[T] = x match {
    case x: T => Some(x)    // if x is of type T i.e. T =:= A
    case _ => None
  }
}

// Exiting paste mode, now interpreting.

import reflect._
defined class Foo

scala> val test = Foo("hi")
test: Foo[String] = Foo(hi)

scala> test.get[Int]
res0: Option[Int] = None

scala> test.get[String]
res1: Option[String] = Some(hi)

If you can throw out the get: 如果你可以抛弃get:

case class Foo[A](x: A)
Seq(Foo("hi"), Foo(1), Foo(2d)).collect { case f @ Foo(x: String) => f }.foreach(println)

results in: 结果是:

Foo(hi)

And the others are similarly trivial. 而其他人同样微不足道。

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

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