Scala检查泛型的类型 [英] Scala check type of generics

查看:136
本文介绍了Scala检查泛型的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ p
$ b

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

def get [T]:Option [T] = x match {
case x:T => Some(x)//如果x是T型的,即T =:= A
case _ =>无


$ b $ val测试= Foo(hi)
assert(test.get [Int] == None)
assert( test.get [String] == Some(hi))

一些奇怪的时间推理失败:
$ b $ pre $ 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])匹配{
case Success(r)=>一些(r)
案例_ =>无



对象Foo扩展应用程序{
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 //即使上面断言通过也不会编译!


解决方案



  scala> :pa 
//进入粘贴模式(ctrl-D完成)

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

def get [T:ClassTag]:Option [T] = x match {
case x:T => Some(x)//如果x是T型的,即T =:= A
case _ =>无
}
}

//退出粘贴模式,现在解释。

import reflect._
定义的类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] =一些(hi)


How do I do something like this in 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)

这篇关于Scala检查泛型的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆