为什么类的第一个参数列表不能是隐式的? [英] Why can't the first parameter list of a class be implicit?

查看:111
本文介绍了为什么类的第一个参数列表不能是隐式的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  scala>类A(隐式a:Int); 
定义类A

scala> class B()(implicit a:Int);
定义类B

scala> new A()(1)
res1:A = A @ 159d450

scala> new B()(1)
res2:B = B @ 171f735

scala> new A(1)
< console>:7:错误:构造函数A的参数太多(隐含a:Int)A
new A(1)

$ p


b $ b

这似乎是一个功能,而不是一个bug,由在scalac资源中的评论


// convert(implicit ...)to
()(implicit ...)如果它只有
参数部分


我很想知道为什么这样做。我觉得很奇怪。

解决方案

我看到的是,隐式参数列表不会替换常规的。因为对于构造函数定义,至少需要一个参数列表,如果没有明确指出,则生成'()'。



虽然这可能是令人困惑的,当没有参数列表时,生成一个空的构造函数。


scala> class A(implicit a: Int);
defined class A

scala> class B()(implicit a: Int);
defined class B

scala> new A()(1)
res1: A = A@159d450

scala> new B()(1)
res2: B = B@171f735

scala> new A(1)
<console>:7: error: too many arguments for constructor A: ()(implicit a: Int)A
       new A(1)

Why does Scalac insert an empty parameter list before the implicit parameter list provided in the class declaration?

This seems to be a feature, not a bug, judging by the commentary in the scalac sources:

// convert (implicit ... ) to ()(implicit ... ) if its the only parameter section

I'm curious to know why this is done. I find it rather surprising.

解决方案

The way I see it is that implicit parameter list does not replace the regular one(s). Since for constructor definitions at least one parameter list is needed, if nothing is indicated explicitly '()' is generated.

While this might be indeed puzzling, it's in line with generating an empty constructor when no parameter lists at all are present.

这篇关于为什么类的第一个参数列表不能是隐式的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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