语法糖是指在计算机语言中添加的某种语法,这种语法对功能并没有影响,只是更方便程序员使用。通常来说,使用语法糖可以增加程序的可读性,从而减少程序代码出错的机会。
对于Java语言来说,最常用的语法糖为泛型、可变参数、装箱、拆箱、循环遍历等,虚拟机执行时并不支持这些语法,它们在编译的阶段会还原回简单的基础语法结构,这个过程称为解语法糖。
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.
For example, many programming languages provide special syntax for referencing and updating array elements. Abstractly, an array reference is a procedure of two arguments: an array and a subscript vector, which could be expressed as get_array(Array, vector(i,j))
. Instead, many languages provide syntax like Array[i,j]
. Similarly an array element update is a procedure of three arguments, something like set_array(Array, vector(i,j), value)
, but many languages provide syntax like Array[i,j] = value
.
Specifically, a construct in a language is called syntactic sugar if it can be removed from the language without any effect on what the language can do: functionality andexpressive power will remain the same.