Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

4. Scala function basis

2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

I. built-in control structure

1. If expression

Val filenameNice = if (! args.isEmpty) args (0) else "default.txt"

2. While cycle

Whether it's while or do...while, we can't call it an expression, we should call it a loop, because they don't calculate a new value. Their value type is Unit, and Unit and () are equal in scala

Def gcdLoop (x: Long, y: Long): Long = {

Var a = x

Var b = y

While (a! = 0) {

Val temp = a

A = b% a

B = temp

}

B

}

Do...while... Expression.

Var line = ""

Do {

Line = scala.io.StdIn.readLine ()

Println ("Read:" + line)

} while (line! = "")

Reassigning var in scala always returns () (that is, Unit)

()! = "will return true forever

Var tempLine = ""

While ((tempLine = scala.io.StdIn.readLine ())! = ") / / This doesn't work!

Println ("Read:" + tempLine)

Because the while loop does not calculate the value, the while code is not so functional and generally contains the var variable

Scala chose to keep while because the code that uses while in some scenarios is still very readable.

Using recursion to eliminate var

Def gcd (x: Long, y: Long): Long =

If (y = = 0) x else gcd (y, x% y)

3. For expression

Iterate over an arbitrary set with for expression

Val filesHere = (new java.io.File ("."). ListFiles

For (file

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report