我如何使Scala中的lambda函数具有通用性? [英] How do I make lambda functions generic in Scala?
问题描述
使得'scala'中的' def'类泛型是相当直接的
def someFunc [T](a:T){//在此处插入
我在这里遇到的问题是如何进行如下通用操作:
val someFunc =(a:Int)=> //在此处插入正文
当然现在a是一个整数,但是我需要做什么使其具有通用性?
val someFunc [T] =(a:T)=>
不会工作, val someFunc = [T](a:T)=>
使它们变得通用,或者我应该坚持'def'变体?
正如Randall Schulz所说,<$ c $ c> def 不会创建函数,而是创建一个方法。但是,它可以返回一个函数,这样就可以在 Predef
中创建通用函数,如 identity
函数。这看起来像这样: def myId [A] =(a:A)=> a
列表(1,2,3)map myId
//列表(1,2,3)
列表(foo)map myId
// List(foo)
但请注意,调用<$ c $没有任何类型信息的c> myId 推断 Nothing
。在上面的例子中,它是有效的,因为类型推断使用 map
的签名,它是 map [B](f:A => B )
,其中 A
是列表的类型,并且 B
被传递给相同作为 A
,因为这是 myId
的签名。
As most of you probably know you can define functions in 2 ways in scala, there's the 'def' method and the lambda method...
making the 'def' kind generic is fairly straight forward
def someFunc[T](a: T) { // insert body here
what I'm having trouble with here is how to make the following generic:
val someFunc = (a: Int) => // insert body here
of course right now a is an integer, but what would I need to do to make it generic?
val someFunc[T] = (a: T) =>
doesn't work, neither does val someFunc = [T](a: T) =>
Is it even possible to make them generic, or should I just stick to the 'def' variant?
As Randall Schulz said, def
does not create a function, but a method. However, it can return a function and this way you can create generic functions like the identity
function in Predef
. This would look like this:
def myId[A] = (a: A) => a
List(1,2,3) map myId
// List(1,2,3)
List("foo") map myId
// List("foo")
But be aware, that calling myId
without any type information infers Nothing
. In the above case it works, because the type inference uses the signature of map
, which is map[B](f: A => B)
, where A
is the type of the list and B
gets infered to the same as A
, because that is the signature of myId
.
这篇关于我如何使Scala中的lambda函数具有通用性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!