为什么 TypeTag 不适用于返回类型? [英] Why does TypeTag not work for return types?

查看:39
本文介绍了为什么 TypeTag 不适用于返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎TypeTags 只适用于被调用方法的参数中使用的类型参数,而不适用于返回类型:

It seems that TypeTags only work for type parameters that are used in the parameters of the called method, and not the return type:

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

import scala.reflect.runtime.universe._

object Test {
  def withParam[T: TypeTag](v: T): T = {
    println(typeOf[T])
    0.asInstanceOf[T]
  }

  def justReturn[T: TypeTag](): T = {
    println(typeOf[T])
    0.asInstanceOf[T]
  }
}

// Exiting paste mode, now interpreting.

import scala.reflect.runtime.universe._
defined module Test


scala> val i: Int = Test.withParam(17)
Int
i: Int = 0

scala> val j: Int = Test.justReturn()
Nothing
j: Int = 0

这和2.9中Manifest的行为是一致的,但是有什么原因做不到,有没有其他方法可以达到这个效果?

This is consistent with the behaviour of Manifest in 2.9, but is there any reason it can't be done, and is there any other way to achieve this effect?

推荐答案

类型系统从最严格的类型开始(即 Nothing,其中不能有实例;如果有它成为能够代表任何事情并做任何事情的上帝般的价值).然后根据需要扩大类型,但由于返回处于逆变位置,因此永远没有理由扩大.如果您确实可以返回 Nothing,那么您就可以在所有情况下进行设置.

The type system starts with the most restrictive type (i.e. Nothing, of which there can be no instances; if there were it would be a godlike value able to stand in for anything and do anything). The type is then widened as needed, but since the return is in contravariant position, there's never a reason to widen. If you actually could return a Nothing, you'd be set in all situations.

然后通过告诉它0Nothing 的实例来颠覆类型系统.当然,这是完全错误的,但是编译器尽职尽责地相信你,你通过将它分配给一个 Int 来挽救这种情况,这就是它一直以来的真实情况.(它也会很高兴地尝试将它分配给 String,然后你会在运行时得到一个异常,因为在这一点上它是荒谬的.)

You then subvert the type system by telling it that 0 is an instance of Nothing. It's completely false, of course, but the compiler dutifully believes you, and you rescue the situation by assigning it to an Int, which is what it really was all along. (It will also happily try to assign it to a String and you'll then get an exception at runtime because at that point it is nonsensical.)

理论上这可以用不同的方式完成,但这是类型推断算法的一个非常基本的部分.

In theory this could be done differently, but this is a pretty basic part of the type inference algorithm.

这篇关于为什么 TypeTag 不适用于返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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