<% 运算符的功能是什么?

3

最近,我看了一个 隐式链 的例子,implicit def foo[C3 <% C](c: C)。我认为我对于<%和(implicit c : C)之间的区别感到困惑。

如果我写成 implicit def bToC[C3 <: C](c: C)(implicit c3 : C3),它会给出编译错误,但是这是为什么呢?implicit def 应该在作用域内啊?

编辑:

有人能解释一下为什么

implicit def aToB[A1 : A](a: A1)(implicit ev: Int => A1): B = new B(a.n, a.n)

implicit def aToB[A1 <: A](a: A1)(implicit ev: Int => A1): B = new B(a.n, a.n)

不起作用吗?

非常感谢!


1
它被称为“视图界定”-https://dev59.com/VW855IYBdhLWcg3wNxkM - user1032985
1个回答

1

[C3 <% C] 意味着 implicit ev: C3 => C。换句话说,一个将 C3 转换为 C 的隐式函数。因此,作用域中的所有 C3 对象都可以是 C 对象。

def intPlus1[A <% Int](a: A) = a + 1
// def intPlus1[A](a: A)(implicit ev: A => Int) = a + 1

implicit def string2int(s: String) = s.toInt // String => Int

intPlus1("100")
intPlus1("100")(string2int)
// the result bark bark

请注意,对于任何 A,都有 A <% A,因为存在一个隐式函数 A => A 已经被 Predef 定义了,因此如果 B <: A,那么也有 B <% A,正如 @rightfold 在评论中提到的一样。 :)

请注意,这包括子类型关系,因此 α <: β → α <% β。 - user1804599
但是为什么 implicit def aToB[A1 : A](a: A1)(implicit ev: Int => A1): B = new B(a.n, a.n) 和 implicit def aToB[A1 <: A](a: A1)(implicit ev: Int => A1): B = new B(a.n, a.n) 无法正常工作? - Xiaohe Dong
@Cloudtech 如果没有提供AA1B的定义,我无法回答这个问题 :P - Ryoichiro Oka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接