当前位置:网站首页>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`()
边栏推荐
- JVMRandom不可设置种子|问题追溯|源码追溯
- 浅浅的谈一下ThreadLocalInsecureRandom
- Ffplay document [easy to understand]
- 关于BRAM IP复位的优先级
- 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
- 深度學習 卷積神經網絡(CNN)基礎
- 处理文件和目录名
- .Net分布式事务及落地解决方案
- 【数字IC验证快速入门】3、数字IC设计全流程介绍
- CADD课程学习(7)-- 模拟靶点和小分子相互作用 (半柔性对接 AutoDock)
猜你喜欢
Parler de threadlocal insecurerandom
无卷积骨干网络:金字塔Transformer,提升目标检测/分割等任务精度(附源代码)...
Leetcode(695)——岛屿的最大面积
Complete interview questions for interviewers and senior Android engineers in front-line Internet enterprises
Unity编辑器扩展 UI控件篇
浅浅的谈一下ThreadLocalInsecureRandom
JVMRandom不可设置种子|问题追溯|源码追溯
Leetcode brush question: binary tree 13 (the same tree)
Let's talk about threadlocalinsecurerandom
IC科普文:ECO的那些事儿
随机推荐
ffplay文档[通俗易懂]
深度学习 卷积神经网络(CNN)基础
【数字IC验证快速入门】8、数字IC中的典型电路及其对应的Verilog描述方法
期货如何网上开户?安不安全?
Common operators and operator priority
Four methods of random number generation | random | math | threadlocalrandom | securityrandom
Win10 x64环境下基于VS2017和cmake-gui配置使用zxing以及opencv,并实现data metrix码的简单检测
解决Thinkphp框架应用目录下数据库配置信息修改后依然按默认方式连接
What is PyC file
leetcode刷题:二叉树16(路径总和)
CCPC 2021威海 - G. Shinyruo and KFC(组合数,小技巧)
Debezium series: idea integrates lexical and grammatical analysis ANTLR, and check the DDL, DML and other statements supported by debezium
关于BRAM IP复位的优先级
走入并行的世界
无卷积骨干网络:金字塔Transformer,提升目标检测/分割等任务精度(附源代码)...
秋招字节面试官问你还有什么问题?其实你已经踩雷了
.Net分布式事務及落地解决方案
Guidelines for application of Shenzhen green and low carbon industry support plan in 2023
Is it safe for Guosen Securities to open an account online?
. Net distributed transaction and landing solution