foo[T](T,T) 的 Scala 类型扩展/推断:T [英] Scala type-widening/inference of foo[T](T,T): T

查看:41
本文介绍了foo[T](T,T) 的 Scala 类型扩展/推断:T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有三个函数:

def foo[T](a:T, b:T): T = a 
def test1 = foo(1, "2") 
def test2 = foo(List(), ListBuffer()) 

虽然 test1 是 Any 类型,但 test2 不会编译.这是为什么?List() 和 ListBuffer() 都是 Any 类型,那么为什么 test2 也不是 Any 类型呢?而且它们都是 SeqFactory 类型,所以 Scala 可以以某种方式推断 test2 的类型是 SeqFactory 吗?

While test1 is of type Any, test2 does not compile. Why is that? Both List() and ListBuffer() are of type Any, so why is test2 is not of type Any as well? Also both of them are of type SeqFactory, so can Scala somehow infer that type of test2 is SeqFactory?

foo(ListBuffer(), "")foo(List(), "") 按预期工作

推荐答案

在我看来像是一个错误.Scala 首先推断 Seq[Nothing]{def seq: Seq[Nothing]{def partner: scala.collection.generic.GenericCompanion[Seq[Any]]};def 伴侣:scala.collection.generic.GenericCompanion[Seq[Any]]},然后决定 ListBuffer[Nothing] 不适合那种类型.

Looks like a bug to me. Scala first infers Seq[Nothing]{def seq: Seq[Nothing]{def companion: scala.collection.generic.GenericCompanion[Seq[Any]]}; def companion: scala.collection.generic.GenericCompanion[Seq[Any]]}, and then decides ListBuffer[Nothing] doesn't really fit that type.

这篇关于foo[T](T,T) 的 Scala 类型扩展/推断:T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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