当前位置:网站首页>Scala basics [HelloWorld code parsing, variables and identifiers]
Scala basics [HelloWorld code parsing, variables and identifiers]
2022-07-05 20:10:00 【hike76】
List of articles
One introduction
1 hello scala world Code parsing
package com.hike.bigdata.scala.chapter01
/** * scala Language is based on java Developed * * package:java In the package * * object: Declare an object , At compile time , It will be compiled into two class files * The declared object is of type : The current object +$ * java: * User user = new User(); * user.setName(); * scala: * Scala01_HelloWorld = new Scala01_HelloWorld$(); * * Scala01_HelloWorld: Object name * * def: Declare the keyword of the method * * main:scala The entry method name of the program , No, main, The program cannot be executed * * (): Method * * args: Array[String]: Parameters * java: * String[] args, Strong type language , Determine the type of variable before running * In the process of development , Variable name is more important than variable type * therefore scala Write the name first , Add a colon between the name and type as a separator * scala: * args:Array[String] * args: Parameter name * Array[String]: Parameter type * : Separator * * Array[String]:Array It's an array type * scala Language is a completely object-oriented language , So all things are objects * Arrays are also objects , There are also their own types , The type is :Array, there [] For generics * * java In the array : * String[]:String Represents the type of elements in an array ,[] Represents an array , * Array in java There is no type in * : Unit => stay scala in : * name : type * Parameter name : Parameter type * Variable name : Variable type * Method name : Method 's return value type * * Unit Represents the return value type ,Unit yes scala New types in , To replace void keyword , Indicates that there is no return value * void Keyword problem : Return value , Add the type of variable , Such as int String * Return no value , Add keywords , Not unified * Equals to equating keywords with types , Unreasonable , So there is Unit type * =: assignment * * {}: Method body * * System.out.println("Hello Scala World"):java Code * scala Language based java Language development , So most of the java The code can be directly in scala Use in * * The code may not need to end with a semicolon ,scala It is recommended that there is only one logic in a line of code , Then the semicolon can be omitted * If there is more than one logic in a line, you need to add a semicolon */
object Scala01_HelloWorld {
def main(args: Array[String]): Unit = {
System.out.println("Hello Scala World")
}
}
2 Decompile
If you only parse the syntax through code , Can't understand its real implementation principle .scala Language is based on Java Language development , So it will also be compiled as class file , Then we can decompile instructions javap -v Class name or decompiler jd-gui.exe see scala Compiled code , Through comparison and java The relationship between languages , To master the implementation principle of specific code .
3 Associated source code
In the use of Scala In the process , To find out Scala The underlying mechanism , Need to check the source code , Then you need to associate and view Scala The source package .
Download the source code , Choose the path .
Two Variables and data types
1 Variable
Variable is a convenient placeholder , Used to refer to the memory address of the computer , Variables take up a certain amount of memory space after they are created . Data types based on variables , The operating system allocates memory and decides what will be stored in reserved memory . therefore , By assigning different data types to variables , You can store integers in these variables , Decimals or letters .
(1) Variable declarations
def main(args: Array[String]): Unit = {
// TODO Variable
// Java Variable declaration in : String name = "zhangsan";
// scala Variable declaration in (1):var Variable name : Variable type = A variable's value
var name_var : String = "zhangsan"
// Some variables in some scenarios , Cannot reassign after initialization
// scala Variable declaration in (2):val Variable name : Variable type = A variable's value
val name_fin : String = "lisi"
}
If the type of variable can be inferred from the value of the variable , Then you can omit the type declaration , Omission here , It's not that you don't declare , But by the Scala The compiler automatically declares the compiled at compile time .
def main(args: Array[String]): Unit = {
// TODO Variable
// In strongly typed languages , The declaration of types should be consistent
// If you know clearly what type of variable value is , Then the type of variable can be omitted without writing
// If polymorphism is used , Type cannot be omitted
var name = "zhangsan"
println(name)
}
(2) Variable initialization
Java Variables in syntax can be initialized before use , however Scala It is not allowed in grammar , Must be displayed for initialization .
def main(args: Array[String]): Unit = {
var username // Error
val username = "zhangsan" // OK
}
(3) Volatile variables
Variable whose value can be changed , It is called a variable variable , But the variable type cannot be changed , Scala Use the keyword... For variable variables in var Make a statement .
def main(args: Array[String]): Unit = {
// User name
var username : String = "zhangsan"
username = "lisi" // OK
username = true // Error
}
(4) Immutable variable
A variable whose value cannot be changed once initialized , Call it an immutable variable .Scala Use keywords in immutable variables val Make a statement , Be similar to Java In language final keyword .
def main(args: Array[String]): Unit = {
// User name
val username : String = "zhangsan"
username = "lisi" // Error
username = true // Error
}
val and var Two modifiers , Recommended val
Java Why is the string in called immutable string : Because in java The definition of string in is private final char[] value;, also String Class does not provide any method to change the content . All methods that operate on strings will produce new strings .
trim Method is used to remove half width spaces at the beginning and end of a string .( Europe and America are half width , Asia and Europe are all corners )
2 identifier
(1) Identifier definition rules
Scala Identifier and java The identifiers of are basically the same , Two forms of flags can be used , Characters, numbers and symbols .
- Characters begin with letters or underscores , It can be followed by letters or numbers , stay Scala in [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly also see do by word mother . however and With open head Of mark knowledge operator by Protect leave Of S c a l a Ed translate device production raw Of mark Records operator send use , Should be use cheng order Should be The avoid Exemption send use Also seen as letters . However, identifiers beginning with are reserved Scala Compiler generated flag usage , Applications should avoid using also see do by word mother . however and With open head Of mark knowledge operator by Protect leave Of Scala Ed translate device production raw Of mark Records operator send use , Should be use cheng order Should be The avoid Exemption send use Start identifier , In case of conflict .
- Scala The naming convention of adopts and Java Allied camel Naming specification , The first character is lowercase , such as toString. The first character of the class name is uppercase . In addition, you should avoid using a flag that ends with an underscores to avoid conflicts .
- Scala The escape flag is used for internal implementation , such as :-> Use c o l o n colon colonminus$greater To represent this symbol .
// and Java The same identifier naming rules
/* Numbers , Letter , Underline ,$ The number can't start You can't use keywords and reserved words Case sensitive There is no limit to length */
val name = "zhangsan" // OK
val name1 = "zhangsan0" // OK
//val 1name = "zhangsan0" // Error
val name$ = "zhangsan1" // OK
val $name = "zhangsan2" // OK
val name_ = "zhangsan3" // OK
val _name = "zhangsan4" // OK
val $ = "zhangsan5" // OK
val _ = "zhangsan6" // OK
//val 1 = "zhangsan6" // Error
//val true = "zhangsan6" // Error
// and Java Different identifier naming rules
// scala Identifiers in can be used to declare operators
val + = "lisi" // OK
println(+)
val - = "lisi" // OK
val * = "lisi" // OK
val / = "lisi" // OK
val ! = "lisi" // OK
//val @ = "lisi" // Error
val @@ = "lisi" // OK
//val # = "lisi" // Error
val ## = "lisi" // OK
val % = "lisi" // OK
val ^ = "lisi" // OK
val & = "lisi" // OK
//val ( = "lisi" // Error
//val ( = "lisi" // Error
//val ) = "lisi" // Error
//val = = "lisi" // Error
val == = "lisi" // OK
//val [ = "lisi" // Error
//val ] = "lisi" // Error
//val : = "lisi" // Error
val :: = "lisi" // OK
//val ; = "lisi" // Error
//val ' = "lisi" // Error
//val " = "lisi" // Error
val "" = "lisi" // OK
val < = "lisi" // OK
val > = "lisi" // OK
val ? = "lisi" // OK
val | = "lisi" // OK
val \ = "lisi" // OK
//val ` = "lisi" // Error
val ~ = "lisi" // OK
val :-> = "wangwu" // OK
val :-< = "wangwu" // OK
// Bear in mind , Being able to declare and be able to use are two different things
// Emoticons
var :-> = "zhangsan"
//var $colon$minus$greater = "zhangsan"
println(:->)
// In general , Identifier naming cannot be used $ start
// Decompiled code
// Compile time , Compile special symbols into converted variable names , The variable name is $ start
String $colon$minus$greater = "zhangsan";
Scala The identifier in cannot be keyword or Reserved words ,Scala Keywords or reserved words in
(2) stay Java Access... In language Scala object
def test(): Unit = {
}
// stay java The code defines
public class TestObject {
public static void main(String[] args) {
Scala02_name.test();
}
}
(3) If variables want to use keywords with specific meanings
var `private` = " Private "
println(`private`)
Thread.`yield`()
边栏推荐
- C language OJ gets PE, OJ of ACM introduction~
- .Net分布式事務及落地解决方案
- leetcode刷题:二叉树11(平衡二叉树)
- Jvmrandom cannot set seeds | problem tracing | source code tracing
- ByteDance dev better technology salon was successfully held, and we joined hands with Huatai to share our experience in improving the efficiency of web research and development
- Elk distributed log analysis system deployment (Huawei cloud)
- 秋招字节面试官问你还有什么问题?其实你已经踩雷了
- E. Singhal and Numbers(质因数分解)
- Is the education of caiqiantang reliable and safe?
- Leetcode skimming: binary tree 17 (construct binary tree from middle order and post order traversal sequence)
猜你喜欢
Leetcode: binary tree 15 (find the value in the lower left corner of the tree)
无卷积骨干网络:金字塔Transformer,提升目标检测/分割等任务精度(附源代码)...
IC科普文:ECO的那些事儿
After 95, Alibaba P7 published the payroll: it's really fragrant to make up this
- Oui. Net Distributed Transaction and Landing Solution
[quick start of Digital IC Verification] 9. Finite state machine (FSM) necessary for Verilog RTL design
leetcode刷题:二叉树10(完全二叉树的节点个数)
Autumn byte interviewer asked you any questions? In fact, you have stepped on thunder
A solution to PHP's inability to convert strings into JSON
【数字IC验证快速入门】3、数字IC设计全流程介绍
随机推荐
【数字IC验证快速入门】8、数字IC中的典型电路及其对应的Verilog描述方法
处理文件和目录名
ByteDance dev better technology salon was successfully held, and we joined hands with Huatai to share our experience in improving the efficiency of web research and development
Database logic processing function
Ffplay document [easy to understand]
淺淺的談一下ThreadLocalInsecureRandom
《乔布斯传》英文原著重点词汇笔记(十二)【 chapter ten & eleven】
Let's talk about threadlocalinsecurerandom
【数字IC验证快速入门】6、Questasim 快速上手使用(以全加器设计与验证为例)
Concept and syntax of function
Debezium series: record the messages parsed by debezium and the solutions after the MariaDB database deletes multiple temporary tables
Go language | 03 array, pointer, slice usage
Is it safe to open a mobile stock account? Is it reliable?
js方法传Long类型id值时会出现精确损失
怎么挑选好的外盘平台,安全正规的?
Unity编辑器扩展 UI控件篇
解决php无法将string转换为json的办法
Tasks in GStreamer
1:引文;
Oracle-表空间管理