Scala关键字介绍和简单示例

2021年4月10日12:42:15 发表评论 1,108 次浏览

关键字或保留字是用于某些内部过程或表示某些预定义动作的语言中的单词。因此, 不允许将这些单词用作变量名或对象。这样做会导致编译时错误。

例子:

//Scala Program to illustrate the keywords 
  
//Here object, def, and var are valid keywords
object Main 
{
     def main(args : Array[String]) 
     {
         var p = 10
         var q = 30
         var sum = p + q
         println( "The sum of p and q is :" +sum);
     }
}

输出如下:

The sum of p and q is :40

Scala包含以下关键字:

abstract
case
catch
class
def
do
else
extends
false
MongoDB
finally
for
forSome
if
implicit
import
lazy
match
new
null
Object
override
package
private
protected
return
sealed
super
this
throw
trait
true
try
type
val
var
while
with
yield
>:
=>
=
<%
<:
<-
#
@
:
+

例子:

//Scala Program to illustrate the keywords 
  
//Here class keyword is used to create a new class
//def keyword is used to create Function
//var keyword is used to create a variable 
class GFG
{
     var name = "Priyanka"
     var age = 20
     var branch = "Computer Science"
     def show()
     {
     println( "Hello! my name is " + name + "and my age is" +age);
     println( "My branch name is " + branch);
     }
}
  
//object keyword is used to define 
//an object new keyword is used to 
//create an object of the given class
object Main 
{
     def main(args : Array[String])
     {
         var ob = new GFG();
         ob.show();
     }
}

输出如下:

Hello! my name is Priyankaand my age is20
My branch name is Computer Science

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: