创建未命名的隐式类或函数 [英] Create unnamed implicit class or function

查看:85
本文介绍了创建未命名的隐式类或函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Scala中创建未命名的隐式类或函数?

Is it possible to create an unnamed implicit class or function in Scala?

例如,如果我有以下隐式类:

For example, if I have the following implicit class:

implicit class ListIntExtras(list: List[Int]) {
  def average = list.sum / list.size
}

我希望能够将其定义为implicit class _(list: List[Int])之类的东西,因为类ListIntExtras的名称从未在任何地方实际使用.

I would prefer to be able to define it as something like implicit class _(list: List[Int]) because the name of the class ListIntExtras is never actually used anywhere.

隐式函数也是如此:

implicit def intToDouble(i: Int): Double = i.toDouble

我想改为将该方法定义为implicit def _(i: Int): ...,因为我再也没有引用其实际名称.

I would like to instead define that method as implicit def _(i: Int): ... because, again, I am never referencing its actual name.

我知道这对于隐式val是可能的.例如,您可以执行implicit val _ = new Config()很有用,因为将其命名为_以外的其他名称似乎是一种浪费,因为它从未被名称引用过.

I know that this is possible for implicit vals. For example, you can do implicit val _ = new Config() which is useful because naming it anything other than _ seems like just a waste as it is never being referenced by name.

推荐答案

Scala 3(Dotty)提供了专用的

Scala 3 (Dotty) provides dedicated extension methods syntax which effectively avoids having to give a name to implicit class, for example

scala> extension (list: List[Int])
     |       def average = list.sum / list.size
     |
def extension_average(list: List[Int]): Int

scala> List(1, 41).average
val res0: Int = 21

这篇关于创建未命名的隐式类或函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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