ayv*_*ngo 4 scala implicit-conversion
我错过了haskell的便捷操作员$所以我决定介绍一个.
class Applayable[-R,T] (val host : Function[R,T]) {
def $: R=>T = host.apply
}
implicit def mkApplayable[R,T] (k : Function[R,T]) : Applayable[R,T] = new Applayable(k)
Run Code Online (Sandbox Code Playgroud)
它已经完全正常工作
val inc : Int => Int = _ + 1
inc $ 1
Run Code Online (Sandbox Code Playgroud)
但失败了
def inc(x:Int) : Int = x+1
inc $ 1
Run Code Online (Sandbox Code Playgroud)
我应该为隐式转换指定什么类型来将def定义转换为Applayable实例?
您不能指定类型来执行您想要的操作:方法不是函数.您可以通过在其后附加魔法下划线将方法转换为(可能部分应用的)函数,如下所示:
def inc(x:Int) : Int = x+1
(inc _) $ 1
Run Code Online (Sandbox Code Playgroud)