python?Scala函數(shù)與訪問修辭符實例詳解
常規(guī)函數(shù)
object Demo {
def main(args: Array[String]) {
println( "Returned Value : " + addInt(5,7) ); // 普通調(diào)用
println( "Returned Value : " + addInt(a=5,b=7) ); // 指定參數(shù)調(diào)用
}
// 方法 默認參數(shù) b = 7
def addInt( a:Int, b:Int = 7 ) : Int = {
var sum:Int = 0
sum = a + b
return sum
}
}
可變參數(shù)函數(shù)
object Demo {
def main(args: Array[String]) {
printStrings("Hello", "Scala", "Python"); // 可變參數(shù)
}
def printStrings( args:String* ) = {
var i : Int = 0;
for( arg <- args ){
println("Arg value[" + i + "] = " + arg );
i = i + 1;
}
}
}
使用名字調(diào)用函數(shù)
apply()函數(shù)接受另一個函數(shù)f和值v,并將函數(shù)f應(yīng)用于v。
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
匿名函數(shù)
Scala支持一級函數(shù),函數(shù)可以用函數(shù)文字語法表達,即(x:Int)=> x + 1,該函數(shù)可以由一個叫作函數(shù)值的對象來表示。 嘗試以下表達式,它為整數(shù)創(chuàng)建一個后繼函數(shù) -
var inc = (x:Int) => x+1
變量inc現(xiàn)在是一種可以像函數(shù)那樣使用的函數(shù) - var x = inc(7)-1
還可以如下定義具有多個參數(shù)的函數(shù):
var mul = (x: Int, y: Int) => x*y
變量mul現(xiàn)在是可以像函數(shù)那樣使用的函數(shù) - println(mul(3, 4))
也可以定義不帶參數(shù)的函數(shù),如下所示:
var userDir = () => { System.getProperty("user.dir") }
變量userDir現(xiàn)在是可以像函數(shù)那樣使用的函數(shù) - println( userDir )
訪問修飾符
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函數(shù)與訪問修辭符實例詳解的詳細內(nèi)容,更多關(guān)于python Scala函數(shù)訪問修辭符的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python3實現(xiàn)爬蟲爬取趕集網(wǎng)列表功能【基于request和BeautifulSoup模塊】
這篇文章主要介紹了Python3實現(xiàn)爬蟲爬取趕集網(wǎng)列表功能,結(jié)合實例形式分析了Python3基于request和BeautifulSoup模塊的網(wǎng)站頁面爬取相關(guān)操作技巧,需要的朋友可以參考下2018-12-12
Pycharm配置opencv與numpy的實現(xiàn)
本文總結(jié)了兩種方法來導(dǎo)入opencv與numpy包,第一種是直接在Pycharm中導(dǎo)入兩個包,第二種是在官網(wǎng)下載相關(guān)文件進行配置,感興趣的小伙伴們可以參考一下2021-07-07
Python自定義sorted排序?qū)崿F(xiàn)方法詳解
這篇文章主要介紹了Python自定義sorted排序?qū)崿F(xiàn)方法詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09
Python實現(xiàn)圖像去噪方式(中值去噪和均值去噪)
今天小編就為大家分享一篇Python實現(xiàn)圖像去噪方式(中值去噪和均值去噪),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12

