gpt4 book ai didi

Scala 检查泛型类型

转载 作者:行者123 更新时间:2023-12-02 14:37:14 26 4
gpt4 key购买 nike

如何在 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"))

我尝试了这个,但遇到了一些奇怪的时间推断失败:

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!!
}

最佳答案

肯定是个骗子,但仓促:

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)

关于Scala 检查泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22341339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com