在宏扩展时生成函数

在宏扩展时生成函数

本文介绍了在宏扩展时生成函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想为一个接受1种类型参数的类生成函数

I would like to generate functions for a class accepting 1 type parameter

case class C[T] (t: T)

取决于T类型参数.

我想生成的函数是由T上可用的函数派生的.

The functions I would like to generate are derived by the functions available on T.

我想确切地是使所有功能可用于T,也可用于C.

What I would like exactly, is to make all the functions available for T, also available for C.

作为C[Int]的示例,我希望能够在C上调用Int上可用的任何函数,并将该函数调用分派到C中包含的Int.

As an example for C[Int], I would like to be able to call on C any function available on Int and dispatch the function call to the Int contained in C.

val c1 = new C(1)
assert(c1 + 1 == 2)

如何通过使用Scala 2或dotty宏来实现此目标?还是可以通过其他方式实现?

How can I achieve this by using Scala 2 or dotty macros?Or, can this be achieved in another way?

推荐答案

您可以通过隐式转换,因此您实际上不需要宏:

What you're trying to do is easily achievable with implicit conversions, so you don't really need macros:

case class C[T] (t: T)

object C { //we define implicit conversion in companion object
  implicit def conversion[T](c: C[T]): T = c.t
}

import scala.language.implicitConversions
import C._

val c1 = C(1)
assert(c1 + 1 == 2) //ok

val c2 = C(false)
assert(!c2 && true) //ok

使用隐式转换意味着,只要编译器注意到类型不匹配,它就会尝试使用隐式函数隐式转换值 em>.

Using implicit conversions means, that whenever compiler would notice, that types don't match, it would try to implicitly convert value applying implicit function.

这篇关于在宏扩展时生成函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:08