scala – 以两种方式声明函数.有什么区别?
发布时间:2020-12-16 18:26:49 所属栏目:安全 来源:网络整理
导读:这两个函数声明是否有效地不同? 如果没有,为什么他们有不同的toString值? scala def f: (Int) = Int = x= x*xf: (Int) = Intscala def f(x: Int) = x*xf: (Int)Int 解决方法 第一个是无参数方法f1,它返回一个Function1 [Int,Int]. scala def f1: (Int = In
这两个函数声明是否有效地不同?
如果没有,为什么他们有不同的toString值? scala> def f: (Int) => Int = x=> x*x f: (Int) => Int scala> def f(x: Int) = x*x f: (Int)Int 解决方法
第一个是无参数方法f1,它返回一个Function1 [Int,Int].
scala> def f1: (Int => Int) = (x: Int) => x * x f1: (Int) => Int 第二个是一个参数方法f2,它接受一个I??nt并返回一个Int. scala> def f2(x: Int): Int = x * x f2: (x: Int)Int 您可以使用相同的语法调用f1和f2,但是当您调用f1(2)时,它会扩展为f1.apply(2). scala> f1 res0: (Int) => Int = <function1> scala> f1(2) res1: Int = 4 scala> f1.apply(2) res2: Int = 2 scala> f2(2) res3: Int = 4 最后,您可以将方法f2“提升”到如下函数. scala> f2 <console>:6: error: missing arguments for method f2 in object $iw; follow this method with `_' if you want to treat it as a partially applied funct ion f2 ^ scala> f2 _ res7: (Int) => Int = <function1> scala> (f2 _).apply(2) res8: Int = 4 练习:f1 _的类型是什么? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读