Scala:“隐式"和类型参数

编程入门 行业动态 更新时间:2024-10-14 20:19:51
本文介绍了Scala:“隐式"和类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在理解以下现象时遇到​​了一些麻烦:

I'm having a little trouble understanding the following phenomenon:

trait Trait[A] { def traitType: String } object Trait { implicit val stringTrait: Trait[String] = new Trait[String] { def traitType: String = "string" } implicit val intTrait: Trait[Int] = new Trait[Int] { def traitType: String = "int" } } class Media[A] { // works def mediaType(implicit t: Trait[A]): String = t.traitType // does not compile def mediaType: String = implicitly[Trait[A]].traitType } object Main { def main(args: Array[String]) { val a = new Media[String] val b = new Media[Int] println(a.mediaType) println(b.mediaType) } }

在上面的代码段中,我展示了 mediaType 方法的2种不同实现(在编译代码时,我将其中之一注释掉了).但是,使用隐式的版本无法编译?我收到以下错误消息:

In the above snippet I show 2 different implementations of the mediaType method (I comment one of them out when compiling the code). However the version using implicitly does not compile? I get the following error message:

impl.scala:19: error: could not find implicit value for parameter e: Trait[A] def mediaType: String = implicitly[Trait[A]].traitType ^ one error found

我确实知道没有可用的Trait [A]隐式值.我不明白为什么A不能解析为实例化Media的类型.我想我在这里对C ++模板的思考太多了,如果有人可以向我指出正确的方向,我将不胜感激.

I do understand that there is no implicit value of Trait[A] available. I don't understand why A does not get resolved to the type Media gets instantiated with. I think I'm thinking too much in terms of C++ templates here and I would be very grateful if someone could give me a pointer into the right direction.

关于, raichoo

Regards, raichoo

推荐答案

编译器需要证据,证明A存在隐式Trait实例.在第一个mediaType实现中,您声明此要求.但是在第二种实现中,从编译器的角度来看,没有这样的保证.因此,为了使其工作,您应该要求Media类的用户提供它.您可以通过上下文绑定来做到这一点:

Compiler needs evidence, that there exist implicit Trait instance for the A. In first mediaType implementation you declare this requirement. But in the second implementation, from the compiler's point of view, there is no such guarantee. So in order to make it work you should ask users of Media class to provide it. You can make this with context bound:

class Media[A : Trait] { def mediaType: String = implicitly[Trait[A]].traitType }

这也可以写得更明确:

class Media[A](implicit val evidence: Trait[A]) { def mediaType: String = implicitly[Trait[A]].traitType }

因此换句话说,默认构造函数需要隐式evidence,并且如果不提供(显式或隐式)类,用户将无法实例化Media类.

So in other words default constructor requires implicit evidence and users would not be able to instantiate Media class without providing it (explicitly or implicitly).

更多推荐

Scala:“隐式"和类型参数

本文发布于:2023-07-14 10:12:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1104070.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   类型   隐式   Scala   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!