加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么传递Int,F [_]参数预期有效?

发布时间:2020-12-16 09:20:12 所属栏目:安全 来源:网络整理
导读:假设我们有一个功能: def bar[F[_],A](x: F[A],y: F[A]) = null 以下所有行为均清楚: bar(List(1,2,3),List(1)) // compile okbar(List(1),Some(1)) // doesn't compile 但, bar(1,List(1)) // compile okbar(1,1) // compile ok 为什么? 附:例如FSiS Pa
假设我们有一个功能:

def bar[F[_],A](x: F[A],y: F[A]) = null

以下所有行为均清楚:

bar(List(1,2,3),List(1)) // compile ok
bar(List(1),Some(1)) // doesn't compile

但,

bar(1,List(1)) // compile ok
bar(1,1) // compile ok

为什么?

附:例如FSiS Part 1 – Type Constructors,Functors,and Kind Projector

解决方法

我认为以下是一个线索(虽然还有一些神秘的含义):

def baz[F[_],A](x: F[A]): F[A] = x

scala> baz("str")
res5: Comparable[String] = str

scala> baz(1)
res6: Any = 1

scala> class Foo
defined class Foo

scala> baz(new Foo)
<console>:15: error: no type parameters for method baz: (x: F[A])F[A] exist so that it can be applied to arguments (Foo)
 --- because ---
argument expression's type is not compatible with formal parameter type;
 found   : Foo
 required: ?F
              baz(new Foo)
              ^
<console>:15: error: type mismatch;
 found   : Foo
 required: F[A]
              baz(new Foo)
                  ^

scala> case class Foo2
warning: there were 1 deprecation warning(s); re-run with -deprecation for details
defined class Foo2

scala> baz(Foo2)
res10: scala.runtime.AbstractFunction0[Foo2] = Foo2

因此,函数bar和baz可以找到它们可以的任何容器类型(对于String,对于case类来说可以是StringFunction0等)来匹配预期的F [_].

猜测:在Int的情况下,我怀疑我们正在为底层字节码中的(boxed)原始类型打入一个特殊的“容器”类型.如果这种特殊类型只能打印回Scala为“Any”,但实际上是一些特殊的类型,我们可以将其视为“任何[_]”,这样可以解释我们看到的结果.作为对原语的特殊处理的说明,请注意,对于非原始简单类型,如上面的(非case)类Foo,它失败.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读