Scala类构造函数中的隐式对象 [英] implicits in scala Class constructors
问题描述
我不明白为什么下面三个示例中只有一个在起作用?是什么导致其他两个错误?
I dont understand why only one out of the three examples below are working? What makes the other two faulty?
class H(implicit a:String, b: Int) {
//Working
}
class H(a:String, implicit b: Int) {
//Not-Working
}
class H(implicit a:String, implicit b: Int) {
//Not-Working
}
推荐答案
在第一种情况下,implicit
并不引用a
,而是引用整个参数列表.这意味着在调用构造函数时可以隐式提供a
和b
"(并使它们在类体中作为隐式提供).从这种意义上讲,您不能为类或方法implicit
设置单个参数.
In the first case implicit
doesn't refer to a
but to the entire parameter list. It means "a
and b
can be provided implicitly when calling the constructor" (and also makes them available as implicits in the class body). You can't make a single parameter of a class or a method implicit
in this sense.
implicit
的第二个用途是标记类型/对象成员.构造函数的参数不是成员,但可以使用val
/var
使其成为成员,如pamu的回答所示;或者,为避免显示为private[this] val
.
The second use of implicit
is to mark a type/object member. Constructor parameters aren't members, but can be made into members by using val
/var
, as in pamu's answer; or, to avoid making it visible, private[this] val
.
这篇关于Scala类构造函数中的隐式对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!