常规函数
1
2
3
4
5
6
7
8
9
10
11
12
|
object Demo { def main(args: Array[String]) { println( "Returned Value : " + addInt( 5 , 7 ) ); / / 普通调用 println( "Returned Value : " + addInt(a = 5 ,b = 7 ) ); / / 指定参数调用 } / / 方法 默认参数 b = 7 def addInt( a: Int , b: Int = 7 ) : Int = { var sum : Int = 0 sum = a + b return sum } } |
可变参数函数
1
2
3
4
5
6
7
8
9
10
11
12
|
object Demo { def main(args: Array[String]) { printStrings( "Hello" , "Scala" , "Python" ); / / 可变参数 } def printStrings( args:String * ) = { var i : Int = 0 ; for ( arg < - args ){ println( "Arg value[" + i + "] = " + arg ); i = i + 1 ; } } } |
使用名字调用函数
apply()函数接受另一个函数f和值v,并将函数f应用于v。
1
2
3
4
5
6
7
8
9
|
object Demo { def main(args: Array[String]) { println( apply ( layout, 10 ) ) } def apply (f: Int = > String, v: Int ) = f(v) def layout[A](x: A) = "[" + x.toString() + "]" } / / $ scalac Demo.scala / / $ scala Demo |
匿名函数
Scala支持一级函数,函数可以用函数文字语法表达,即(x:Int)=> x + 1,该函数可以由一个叫作函数值的对象来表示。 尝试以下表达式,它为整数创建一个后继函数 -
var inc = (x:Int) => x+1
变量inc现在是一种可以像函数那样使用的函数 - var x = inc(7)-1
还可以如下定义具有多个参数的函数:
var mul = (x: Int, y: Int) => x*y
变量mul现在是可以像函数那样使用的函数 - println(mul(3, 4))
也可以定义不带参数的函数,如下所示:
var userDir = () => { System.getProperty("user.dir") }
变量userDir现在是可以像函数那样使用的函数 - println( userDir )
访问修饰符
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class Outer { class Inner { private def f1() { println( "f" ) } protected def f2() { println( "f" ) } def f3() { println( "f" ) } # 保护作用域Scala中的访问修饰符可以通过限定符进行扩充。形式为private [X]或protected [X]的修饰符表示为访问是私有或受保护的“最多”到X,其中X指定一些封闭的包,类或单例对象。 private[professional] var workDetails = null private[society] var friends = null private[this] var secrets = null class InnerMost { f() / / OK } } (new Inner).f() / / Error: f is not accessible } |
以上就是python Scala函数与访问修辞符实例详解的详细内容,更多关于python Scala函数访问修辞符的资料请关注服务器之家其它相关文章!
原文链接:https://juejin.cn/post/7127307229371301918