根据类型参数生成函数 [英] Generate functions based on type parameter
问题描述
我想为一个接受1个类型参数的类生成函数,该参数包装一个按名称值.
I would like to generate functions for a class accepting 1 type parameter, which wraps a by name value.
class C[T](_t: => T) {
def 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 get all the functions available for T
, change their contract and implementation in a programmatic way, and make them available for C
.
-
通过更改其合同,我的意思是更改其签名,以便它们返回
C[R]
,其中R
代表原始函数的返回类型.
By changing their contract, I mean changing their signature so they return
C[R]
, whereR
stands for the return type of the original function.
通过更改其实现,我的意思是在返回结果之前将结果包装在C
中.
By changing their implementation, I mean wrapping the result inside C
before returning it.
例如
def +(that: Int): Int =
this + that
将在C[Int]
上以
def +(that: Int): C[Int] =
C(this.t + that)
这样做是为了消除必须包装C
内部的计算以保持其未评估状态的样板.
This would be done in order to remove the boilerplate of having to wrap inside C
a computation in order to keep it non-evaluated.
例如
val c1 = new C(1)
val c2: C[Int] = C(c1.t + 1)
c2.t == 2
也可以表示为
val c2: C[Int] = c1 + 1
c2.t == 2
如何通过使用Scala 2或dotty宏来实现此目标?还是可以通过其他方式实现?
How can I achieve this by using Scala 2 or dotty macros? Or, can this be achieved in another way?
推荐答案
在您之前的或使类隐式
implicit class C[T](_t: => T) {
def t: T = _t
}
关于宏,由于要添加定义,因此需要宏注释,而不是 def宏. Dotty没有宏注释,它只有内联宏,例如Scala 2 def宏.
Regarding macros, since you want to add definitions you would need macro annotations rather than def macros. Dotty doesn't have macro annotations, it has only inline macros like Scala 2 def macros.
宏注释也无济于事.定义类C[T]
时,不知道T
是什么(只有在调用站点知道),因此不知道要添加什么方法.
And macro annotations don't help either. When you define class C[T]
it's not known what T
is (this will be known only at call site), so it's not known what methods to add.
Dotty也有隐式转换
Dotty has implicit conversions too
given [T] as Conversion[T, C[T]] = new C(_)
given [T] as Conversion[C[T], T] = _.t
(当前是given
,以前是implicit
,然后是implied
,然后是delegate
,当前为0.17 given
,可以再次更改).
(currently it's given
, formerly it was implicit
, then implied
, then delegate
, currently in 0.17 given
, this can change again).
似乎不允许Conversion[(=> T), C[T]]
.
这篇关于根据类型参数生成函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!