可以省略变量类型
val a = "apple"
val b: String = "apple"
方法
可以省略返回值类型
def add1(a:Int,b:Int) ={
a+b
}
def add2(a:Int,b:Int):Int ={
a+b
}
方法参数不能省略类型
可以同时省略返回值类型和等号
必须同时
def add1(a:Int,b:Int){
a+b
}
不可以单独省略等号
方法体简单时可以省略花括号
def add1(a:Int,b:Int):Int =a+b
可以同时省略花括号和返回值类型
def add1(a:Int,b:Int) =a+b
调用无参方法时可以省略()
这个在scala源码中很常见!隐蔽性很强
def main(args: Array[String]): Unit = {
add1
}
def add1() = {
println("test")
}
定义无参方法时可以省略()
def main(args: Array[String]): Unit = {
add1
}
def add1 = {
println("test")
}
一个参数的方法可以省略.和()
scala> val arr = Array(1, 2, 3)
arr: Array[Int] = Array(1, 2, 3)
scala> arr.take(2)
res3: Array[Int] = Array(1, 2)
//arr对象调用了take方法
//源码中这种调用常常让人迷糊
scala> arr take 2
res4: Array[Int] = Array(1, 2)
override /*TraversableLike*/
def take(n: Int): Repr = slice(0, n)
scala> val arr = Array(1, 2, 3)
arr: Array[Int] = Array(1, 2, 3)
scala> arr.map(x=>x*2)
res5: Array[Int] = Array(2, 4, 6)
//虽然一个参数,但如果是函数,不能这么调用
scala> arr map x=>x*2
<console>:1: error: ';' expected but '=>' found.
arr map x=>x*2
^
无参的方法调用可以省略.
scala> val arr = Array(1, 2, 3)
arr: Array[Int] = Array(1, 2, 3)
scala> arr.toList
res6: List[Int] = List(1, 2, 3)
//这种调用也是让人迷惑
scala> arr toList
warning: there was one feature warning; re-run with -feature for details
res7: List[Int] = List(1, 2, 3)
再比如,方法 属性 傻傻分不清楚
scala> 1 toString
warning: there was one feature warning; re-run with -feature for details
res9: String = 1
scala> List(1,2,3) size
warning: there was one feature warning; re-run with -feature for details
res10: Int = 3