繁体   English   中英

这两种方法定义之间的区别

[英]Difference between these two method definitions

这两个定义有什么区别?:

def sayTwords(word1: String, word2: String) = println(word1 + " " + word2)
def sayTwords2(word1: String)(word2: String) = println(word1 + " " + word2)

每个人的目的是什么?

第二个是咖喱,第一个不是。 有关为什么选择curry方法的讨论,请参阅Scala中curried函数背后的基本原理是什么?

sayTwords2允许部分应用该方法。

val sayHelloAnd = sayTwords2("Hello")
sayHelloAnd("World!")
sayHaelloAnd("Universe!")

请注意,您也可以以相同的方式使用第一个函数。

val sayHelloAnd = sayTwords("Hello", _:String)
sayHelloAnd("World!")
sayHelloAnd("Universe!")
def sayTwords(word1: String, word2: String) = println(word1 + " " + word2)
def sayTwords2(word1: String)(word2: String) = println(word1 + " " + word2)

第一个包含单个参数列表。 第二个包含多个参数列表。

他们在以下方面有所不同:

  1. 部分应用程序语法。 注意:

     scala> val f = sayTwords("hello", _: String) f: String => Unit = <function1> scala> f("world") hello world scala> val g = sayTwords2("hello") _ g: String => Unit = <function1> scala> g("world") hello world 

    前者具有位置语法的好处。 因此,您可以在任何位置部分应用参数。

  2. 类型推断。 Scala中的类型推断按参数列表工作,并从左到右。 因此,考虑到一个案例,人们可能会促进更好的类型推断。 注意:

     scala> def unfold[A, B](seed: B, f: B => Option[(A, B)]): Seq[A] = { | val s = Seq.newBuilder[A] | var x = seed | breakable { | while (true) { | f(x) match { | case None => break | case Some((r, x0)) => s += r; x = x0 | } | } | } | s.result | } unfold: [A, B](seed: B, f: B => Option[(A, B)])Seq[A] scala> unfold(11, x => if (x == 0) None else Some((x, x - 1))) <console>:18: error: missing parameter type unfold(11, x => if (x == 0) None else Some((x, x - 1))) ^ scala> unfold(11, (x: Int) => if (x == 0) None else Some((x, x - 1))) res7: Seq[Int] = List(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1) scala> def unfold[A, B](seed: B)(f: B => Option[(A, B)]): Seq[A] = { | val s = Seq.newBuilder[A] | var x = seed | breakable { | while (true) { | f(x) match { | case None => break | case Some((r, x0)) => s += r; x = x0 | } | } | } | s.result | } unfold: [A, B](seed: B)(f: B => Option[(A, B)])Seq[A] scala> unfold(11)(x => if (x == 0) None else Some((x, x - 1))) res8: Seq[Int] = List(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM