将属性添加到类型而不是类型的实例的隐式转换 [英] implicit conversions that add properties to a type, rather than to an instance of a type

查看:76
本文介绍了将属性添加到类型而不是类型的实例的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一些旧的Scala帖子,以更好地理解类型类,然后我跑了 在这个中,这似乎很有用,但是示例似乎已经过时了.

I was reading through some older Scala posts to better understand type classes, and I ran across this one that seemed quite useful, but the example seems to have gotten stale.

有人可以帮助我找出执行Phillipe意图的正确方法吗?这是代码

Can someone help me figure out the correct way to do what Phillipe intended ? Here is the code

trait Default[T] { def value : T }

implicit object DefaultInt extends Default[Int] {
  def value = 42
}

implicit def listsHaveDefault[T : Default] = new Default[List[T]] {
  def value = implicitly[Default[T]].value :: Nil
}

default[List[List[Int]]]

当复制/粘贴并在REPL中运行时,我得到此信息>

When copy/pasted and run in REPL, i get this>

    scala> default[List[List[Int]]]
    <console>:18: error: not found: value default
                  default[List[List[Int]]]
                  ^

推荐答案

这与Scala版本无关.如果您阅读 @Philippe的答案,您会发现default方法根本就没有定义.在任何 Scala版本中都无法使用.

This doesn't have anything to do with the Scala version. If you read @Philippe's answer, you will notice that the default method simply isn't defined anywhere. That will not work in any Scala version.

它应该看起来像这样:

def default[T: Default] = implicitly[Default[T]].value

这篇关于将属性添加到类型而不是类型的实例的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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