组成函数接口的Scala
我有以下功能接口:组成函数接口的Scala,scala,Scala,我有以下功能接口: scala> object FromString extends (String => Int) { | def apply(a: String) = a.length | } defined object FromString scala> object FromInt extends (Int => Int) { | def apply(a: Int) = a * a | } defined object
scala> object FromString extends (String => Int) {
| def apply(a: String) = a.length
| }
defined object FromString
scala> object FromInt extends (Int => Int) {
| def apply(a: Int) = a * a
| }
defined object FromInt
如何使用函数组合来有效地链接上面的函数接口?您可以调用和,或者直接在该单例对象上进行组合,因为它们扩展了Function1特性:
(FromString andThen FromInt)("abc") // 9
您可以直接对该单例对象调用andThen或compose,因为它们扩展了Function1特性:
(FromString andThen FromInt)("abc") // 9
您只需要一个函数复合运算符吗?您可以使用
和然后使用val f:String=>Int=FromString,然后使用fromtint
我不能只使用FromString(“a”)和fromtint(…)。。。像这样的?当我尝试时它失败了它必须是接口而不是函数?它将使用函数而不是对象。嗯。。。我称之为功能接口,必须有可能组成它们scala>val f=((s:String)=>s.length)然后((x:Int)=>x*x))f:String=>Int=scala.Function1$$Lambda$1109/368603167@4ed9f7b1scala>f(“你好世界”)res9:Int=121
。像这样的东西是不能满足您的需要的?您只是想要一个函数合成操作符吗?您可以使用和然后使用val f:String=>Int=FromString,然后使用fromtint
我不能只使用FromString(“a”)和fromtint(…)。。。像这样的?当我尝试时它失败了它必须是接口而不是函数?它将使用函数而不是对象。嗯。。。我称之为功能接口,必须有可能组成它们scala>val f=((s:String)=>s.length)然后((x:Int)=>x*x))f:String=>Int=scala.Function1$$Lambda$1109/368603167@4ed9f7b1scala>f(“你好世界”)res9:Int=121
。像这样的东西是不能满足你的需要的?我觉得这很合理!这听起来很合理!