如何将(隐式转换:String => A)表示为视图绑定

发布于 2024-12-01 05:12:13 字数 233 浏览 4 评论 0原文

我问自己什么是视图绑定相当于

(implicit conv: String => A)

我的第一次尝试是简单地声明类型参数A如下:

[String <% A]

但是Scala编译器抱怨“未找到:类型A”< /em>。

有什么建议吗?

I am asking myself what would be the view bound equivalent to

(implicit conv: String => A)

My first attempt was to simply declare the type parameter A as follows:

[String <% A]

But the Scala compiler complains with "not found: type A".

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

在风中等你 2024-12-08 05:12:13

-- 修订后的帖子 --

语法[B <% A] 实际上绑定了一个新类型B。因此

class Foo[A, String <% A]

相当于

class Foo[A, String](implicit $conv: String => A)

String 是任意类型参数,而不是您正在考虑的类。

我认为命名隐式转换可能是您最好的选择,

class Foo[A](implicit conv: String => A)

现在 String 的类型没有被隐藏。

摘要:视图边界对于从引入的类型参数进行转换非常有用,而不是从类型参数进行转换。

-- Revised post --

The syntax [B <% A] actually binds a new type B. So

class Foo[A, String <% A]

is equivalent to

class Foo[A, String](implicit $conv: String => A)

where String is an arbitrary type parameter, not the class you're thinking of.

I think the named implicit conversion is probably your best option,

class Foo[A](implicit conv: String => A)

where now the type of String is not shadowed.

Summary: view bounds are useful as conversions from the introduced type parameter, not to the type parameter.

哆兒滾 2024-12-08 05:12:13

那不是视图界限。视图边界表示类型参数 A 是有边界的,因为它可以被视为(转换为)类型 B。你有反转类型和类型参数,所以它不符合条件。

为了让事情更清楚,绑定是对“自由”类型(类型参数)的限制。例如:

type A <: String // A has an upper bound
type A >: String // A has a lower bound

所以视图界限也是一种限制——通过一种非常不同的机制施加的限制。因此,它只能应用于类型参数,而不能应用于类型。

当然,说 String =>; A 必须存在也是一种绑定,但没有名称或语法糖。

That is not a view bound. A view bound says that a type parameter A is bounded in that it can be viewed (converted to) as a type B. What you have inverted type and type parameter, so it doesn't qualify.

To make things more clear, a bound is a limit on a "free" type -- a type parameter. For example:

type A <: String // A has an upper bound
type A >: String // A has a lower bound

So a view bound is also a limit -- one imposed through a very different mechanism. As such, it can only be imposed on a type parameter, not on a type.

Surely, saying String => A must exist is also a kind of bound, but not one that has a name or syntactic sugar for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文