简体   繁体   English

Val和def的函数文字引用

[英]Function Literal referencing by val and def

I'm trying to understand the crucial difference between these two approaches of referencing / defining Function Literal (reference to anonymous function ): 我试图理解这两种引用/定义Function Literal (引用anonymous function )的方法之间的关键区别:

By val val

scala> val v2 = new Function[Int, Int] {
     | def apply(a: Int): Int = a + 1
     | }
v2: Int => Int = <function1>

And by def 并通过def

scala> def f2 = new Function[Int, Int] {
     | def apply(a: Int): Int = a + 1
     | }
f2: Int => Int

It seems that it pretty much the same in terms of use. 它在使用方面似乎几乎相同。 I either can pass v2 or f2 to the function that accepts (Int) => Int as an argument. 我要么将v2f2传递给接受(Int) => Int作为参数的函数。 Passing arguments to its.. 将参数传递给它..

I guess or the case of v2 it creates an Function1 object that refers to the Function1 object.. like a proxy ? 我想还是V2它创建了一个的情况下Function1是指对象Function1对象..喜欢一个proxy

Ok.. My question is: what is advantage and disadvantages of 1th and 2nd approach? 好的..我的问题是: 第1和第2种方法的优点和缺点什么?

And of it is defined by def , is it still Function Literal ? 它由def定义,它仍然是Function Literal吗?

First of all, neither of your examples are actually function literals —you're creating a Function instance in the plain old sugar-free way, and in fact you could use this approach ( new Function { ... } ) to create an instance of scala.Function from Java code. 首先,你的例子都不是实际的函数文字 - 你以简单的无糖方式创建一个Function实例,实际上你可以使用这种方法( new Function { ... } )来创建一个实例来自Java代码的scala.Function

The following are both function literals, and are exactly equivalent to your definitions: 以下是函数文字,并且与您的定义完全等效:

val v2 = (a: Int) => a + 1
def f2 = (a: Int) => a + 1

The only real difference here is that the val will create a single instance once and for all, no matter how many times you use v2 (and even if you never use it), while the def will create a new instance every time (or not at all, if you never use it). 这里唯一真正的区别是val将一劳永逸地创建一个实例,无论你使用v2多少次(即使你从不使用它), def也会每次创建一个新实例(或者不是根本,如果你从来没有使用它)。 So you'll generally want to go with a val . 所以你通常想要一个val

There are cases, however, where you need to use def . 但是,有些情况下您需要使用def Consider the following: 考虑以下:

def myIdentity[A] = (a: A) => a

There's no way we could write this as a val , since Scala doesn't have polymorphic functions in this sense (for any instance of Function[A, B] , A and B have to be concrete types). 我们无法将其写为val ,因为Scala在这个意义上没有多态函数(对于Function[A, B]AB任何实例都必须是具体类型)。 But we can define a polymorphic method that returns a function, and when we write eg myIndentity(1) , the A will be inferred to be Int , and we'll create (and apply) a Function[Int, Int] exactly as you'd expect. 但是我们可以定义一个返回函数的多态方法,当我们编写例如myIndentity(1)A将被推断为Int ,我们将创建(并应用)一个Function[Int, Int]就像你一样我期待。

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

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