What does => and () => mean in Scala

本文深入探讨了Scala中函数类型的语法糖特性,通过实例解释了如何使用箭头符号(=>)来定义不同参数数量的函数,包括一元函数(Function1)和零参数函数(Function0),并展示了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class.

For example, the type Int => String, is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String.

  scala> val f: Function1[Int,String] = myInt => "my int: "+myInt.toString
  f: (Int) => String = <function1>

  scala> f(0)
  res0: String = my int: 0

  scala> val f2: Int => String = myInt => "my int v2: "+myInt.toString
  f2: (Int) => String = <function1>

  scala> f2(1)
  res1: String = my int v2: 1

Here myInt is binded to the argument value passed to f and f2.

() => T is the type of a function that takes no arguments and returns a T. It is equivalent to Function0[T]() is called a zero parameter list I believe.

 scala> val f: () => Unit = () => { println("x")}
 f: () => Unit = <function0>

 scala> f()
 x

scala> val f2: Function0[Unit] = () => println("x2")
f: () => Unit = <function0>

scala> f2()
x2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值