A Deeper Look at the Scala Syntax (scala block)

本文探讨Scala中代码块的特性及其在函数定义中的应用,展示如何通过代码块实现更简洁、灵活的函数语法糖,提高代码可读性和效率。
Scala 

 is an object-oriented, statically-typed and functional programming language for the JVM. The strength of Scala lies in it’s powerful syntax which allows to write readable, manageable code which is short and concise – and it comes with great support for common design pattern (i.e. a special keyword for implementing the singleton design pattern).

There are plenty of good tutorials and introductions for learning Scala in the web, but only a few mention the great possibilities programmers have to extend Scala or even build an own domain specific language using Scala without being forced to use macros as seen in LISP-like languages.

One interesting feature of Scala are “blocks” which work quite different then code blocks in Java and C++ although they use the same syntax. A block in Scala is rather a sequence of expressions which is evaluated successively and it returns the value of the last expression. Just think of them as the “do” function in LISP. Blocks are surrounded by curly braces and the expressions they hold are separated by semicolons.

1
2
scala> { val x = 2 ; x + 5 }
res 0 : Int = 7

Thanks to some syntactic sugar the semicolon can be replaced by a line break which becomes handy in larger blocks.

1
2
3
4
5
scala> {
   val x = 5
   x + 5
}
res 1 : Int = 10

Because blocks are just expressions they can be used, of course, like every other expression. They can be stored in variables, returned by functions and also be used as parameters for functions:

1
2
3
4
5
6
7
8
scala> println( 2 + 5 )
7
 
scala> println {
   val x = 2
   x + 5
}
7

The attentive reader might already have a glimpse of the potential power of such a syntax. This tiny, simple feature allows us to define functions which look and feel more like keywords of the language’s syntax. Just think of a function which measures the time a given piece of code needs to be executed. How would you write something like this in Java or even in a dynamic language like Python? In Scala this can easily be done by writing a function which expects a code block and handles it like a function which returns a value of any type to simulate lazy parameter evaluation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def time(code : = > Any) : Any = {
   val time = System.currentTimeMillis
   val result = code
   println( "time elapsed: " + (System.currentTimeMillis-time))
   result
}
 
def fib(n : Int) : Int = if (n < 2 ) 1 else fib(n- 1 )+fib(n- 2 )
 
scala> time {
   fib( 40 )
}
 
time elapsed : 1020
res 2 : Any = 165580141

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值