首页  

Scala中apply的用法     所属分类 scala 浏览量 565
Scala中的 apply 方法有着不同的含义, 
对于函数来说该方法意味着调用function本身 

Every function value is an instance of some class that extends one of several FunctionN traits in package scala, 
such as Function0 for functions with no parameters, Function1 for functions with one parameter, and so on. 
Each FunctionN trait has an apply method used to invoke the function.


在Scala语言中, 函数也是对象, 每一个对象都是scala.FunctionN(1-22)的实例, 其中N是函数参数的数量 

scala> val f = (x: Int) => x + 1
f: Int => Int = $Lambda$1019/386201215@e4d2696

scala> f.apply(2)
res0: Int = 3

scala> f(2)
res1: Int = 3

用作工厂方法

List.apply(1, 2, 3) 创建List对象
apply方法定义在List类的伴生对象中

可简化通过 List(1, 2, 3) 创建List实例


scala> List.apply(1, 2, 3)
res2: List[Int] = List(1, 2, 3)

scala>  List(1, 2, 3)
res3: List[Int] = List(1, 2, 3)

集合类的 apply 方法


检索
scala>  Seq(1, 2, 3).apply(1)
res4: Int = 2

判断是否存在
scala> Set(1, 2, 3).apply(2)
res5: Boolean = true

根据键查找
scala> Map("a" -> "1", "b" -> "2").apply("a") 
res6: String = 1

上一篇     下一篇
scala implicit 隐式类

2022中国SaaS领域新形势

Scala object 伴生对象

大数据工程师入门概述

scala 模式匹配

scala Option Some None