Scala鑄造

Scala中的類型 (Types in Scala)

Type also know as data type tells the compiler about the type of data that is used by the programmer. For example, if we initialize a value or variable as an integer the compiler will free up 4 bytes of memory space and it will hold 32 bit signed integer type.

類型也稱為數據類型,它告訴編譯器程序員使用的數據類型。 例如,如果我們將一個值或變量初始化為整數,則編譯器將釋放4個字節的內存空間,并將保留32位帶符號整數類型。

在Scala中進行類型轉換 (Type Casting in Scala)

Type casting is the process of converting that type from one to another. For example, We can convert int type to float type in Scala.

類型轉換是將類型從一種轉換為另一種的過程。 例如,我們可以在Scala中將int類型轉換為float類型。

But this conversion cannot be two ways and is derived from certain types i.e. the conversion from one type to another is possible and the reverse is not. This is due to the different sizes of data type and conversion from type of size greater to a smaller one might lead to data losses.?

但是這種轉換不能是兩種方式,并且是從某些類型派生的,即可以從一種類型轉換為另一種類型,而相反則不能。 這是由于數據類型的大小不同,從大小類型轉換為較小類型可能會導致數據丟失。

The following diagram shows which conversion is possible:

下圖顯示了可能的轉換:

Scala | Type Casting

Know more about type hierarchy: Scala type hierarchy.

了解有關類型層次結構的更多信息: Scala類型層次結構 。

The following conversions are valid:

以下轉換有效:

Character -> Integer
Short -> Integer
Byte -> Integer
Integer -> Long
Long -> Float 
Float -> Double

But, the reverse conversions can be done but are invalid due to data losses. For example, Double -> Float is invalid.

但是,可以進行反向轉換,但是由于數據丟失而無效。 例如, Double-> Float無效。

類型轉換的類型 (Types of Type Casting)

There can be two types of typecasting as all programming languages have,

所有編程語言都有兩種類型轉換,

  1. Implicit type casting

    隱式轉換

  2. Explicit type casting

    顯式鑄造

1)隱式轉換 (1) Implicit type casting)

In implicit type Casting of type in Scala the compiler itself cast the type of the value/variable. This conversion can be lossy i.e. in some cases data may be lost. For example, in the case of division of two int values which can return a non-integer (float/ double) value, the result will be of integer type which can lead to data loss.

在Scala中的隱式類型轉換中,編譯器本身將轉換值/變量的類型。 這種轉換可能是有損的,即在某些情況下可能會丟失數據。 例如,如果將兩個int值相除并且可以返回一個非整數(浮點/雙精度)值,則結果將是整數類型,這會導致數據丟失。

Scala program to demonstrate example of implicit type casting

Scala程序演示隱式類型轉換的示例

object myObject {
def main(args: Array[String]) {
val a : Int = 3421
println("a has value: " + a + " and its type is: " + a.getClass)
val c = a / 4 // result is 855.25 but will be converted to Int
println("The value of a/4: " + c + " and its type is: " + c.getClass)
}
}

Output:

輸出:

a has value: 3421 and its type is: int
The value of a/4: 855 and its type is: int

In the above code, we have created a value a of type integer with value 3421, then we have divided a by 4 and stored the result in value c.? This division leaves to a decimal point value but due to implicit type conversion, it is stored in integer type which two losses.

在上面的代碼中,我們創建了一個值為3421的整數類型的值a 然后將a除以4并將結果存儲在值c中 。 該除法保留一個小數點值,但是由于隱式類型轉換,它存儲在整數類型中,該類型有兩個損失。

This problem can be solved by using explicit conversion to avoid data loss but in some cases that may lead to excessive memory wastage.

通過使用顯式轉換來避免數據丟失,可以解決此問題,但是在某些情況下,這可能會導致過多的內存浪費。

2)顯式類型轉換 (2) Explicit Type Conversion)

The explicit type conversion is user-defined type conversion i.e. the user will decide that final data type of the value/variable.

顯式類型轉換是用戶定義的類型轉換,即用戶將決定值/變量的最終數據類型。

The type conversion of value types can be done directly but for reference types, the conversion required asInstanceOf method.

值類型的類型轉換可以直接完成,但對于引用類型,則需要asInstanceOf方法進行轉換。

As the asInstanceOf method is a concrete method of Any Class, it can be used for type conversion of AnyVal object and AnyRef objects too (object conversion).

由于asInstanceOf方法是Any Class的具體方法,因此它也可以用于AnyVal對象和AnyRef對象的類型轉換( 對象轉換 )。

Let's see the examples of both the methods in action:

讓我們來看一下這兩種方法的示例:

Example 1: Explicit type conversion

示例1:顯式類型轉換

object myObject {
def main(args: Array[String]) {
// Type conversion from Short to Long 
val a : Short = 3421
println("a has value: " + a + " and its type is: " + a.getClass)
val b : Long = a // converting type from short to long
println("Type casting from Short to Long")
println("b has value: " + b + " and its type is: " + b.getClass)
// Type conversion from Char to Float 
val ch : Char = 'S'
println("\nch has value: " + ch + " and its type is: " + ch.getClass)
val fl : Float = ch // converting type from Char to Float
println("Type casting from Character to Float")
println("fl has value: " + fl + " and its type is: " + fl.getClass)
}
}

Output:

輸出:

a has value: 3421 and its type is: short
Type casting from Short to Long
b has value: 3421 and its type is: longch has value: S and its type is: char
Type casting from Character to Float
fl has value: 83.0 and its type is: float

In the above code, we have done two types of conversions. One from short to long and other from char to float.

在上面的代碼中,我們完成了兩種類型的轉換。 一個從短到長 ,另一個從char到float。

For short to long, we have created variable a of type short that stores a value 3421, and then we have created another variable b of type long which is initialized with the value of short.

對于short到long,我們創建 short類型的變量a ,存儲了一個值3421,然后創建了另一個long類型的變量b,并使用short的值對其進行了初始化。

For char to float, we have created variable ch of type char that stores a value S, and then we have created another variable fl of type float which is initialized with the value of char. This will have the float type of ASCII value of 'S'.

為了使char浮動,我們創建了char類型的變量ch ,存儲了一個值S ,然后創建了另一個float類型的變量fl,該變量使用char的值進行了初始化。 這將具有ASCII值“ S”的浮點類型。

Example 2: Explicit conversion using asInstanceOf method

示例2:使用asInstanceOf方法的顯式轉換

object myObject {
def main(args: Array[String]) {
// Type conversion from Short to Flaot 
val a : Short = 3421
println("a has value: " + a + " and its type is: " + a.getClass)
val b = a.asInstanceOf[Double] // converting type from short to long
println("Type casting from Short to Double")
println("b has value: " + b + " and its type is: " + b.getClass)
// Type conversion from Char to Int 
val ch : Char = 'S'
println("\nch has value: " + ch + " and its type is: " + ch.getClass)
val intVal = ch.asInstanceOf[Int] // converting type from Char to Int
println("Type casting from Character to Int")
println("intVal has value: " + intVal + " and its type is: " + intVal.getClass)
}
}

Output:

輸出:

a has value: 3421 and its type is: short
Type casting from Short to Double
b has value: 3421.0 and its type is: doublech has value: S and its type is: char
Type casting from Character to Int
intVal has value: 83 and its type is: int

In the above code, we have done two types of conversions. One from short to Double and other from char to int.

在上面的代碼中,我們完成了兩種類型的轉換。 一個從short到Double ,另一個從char到int。

For short to Double, we have created variable a of type short that stores a value 3421, and then we have created another variable b of type Double which is initialized using the asInstanceOf method for conversion of type.

對于Double的short,我們創建 short類型的變量a ,存儲了一個值3421 ,然后創建了另一個Double類型的變量b,使用asInstanceOf方法初始化了該變量b以進行類型轉換。

For char to float, we have created variable ch of type char that stores a value S, and then we have created another variable intVal of type int which is initialized with the value of char using the asInstanceOf method. The data in the intVal is the ASCII value for the character.

對于char到浮子,我們已經創建char類型的變量CH,其存儲的值S,然后我們已經創建了與使用asInstanceOf方法炭的值進行初始化int類型的另一個變量INTVAL。 intVal中的數據是字符的ASCII值。

翻譯自: https://www.includehelp.com/scala/type-casting.aspx

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/540548.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540548.shtml
英文地址,請注明出處:http://en.pswp.cn/news/540548.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

/ 卡路里_最大卡路里

/ 卡路里Problem statement: 問題陳述: Shivang is very foodie but he has a diet plan. He has an array of elements indicating the calorie of food he can consume on that day. In his diet plan, he can’t eat on for three consecutive days. But since …

[轉載] Python類中的私有變量和公有變量

參考鏈接: Python中的私有變量 我們這里就直奔主題,不做基礎鋪墊,默認你有一些Python類的基礎,大家在看這篇博客的時候,如果基礎知識忘了,可以去菜鳥教程 從一個簡單的類開始 class A(): #定義一…

OpenCV探索之路(二十五):制作簡易的圖像標注小工具

搞圖像深度學習的童鞋一定碰過圖像數據標注的東西,當我們訓練網絡時需要訓練集數據,但在網上又沒有找到自己想要的數據集,這時候就考慮自己制作自己的數據集了,這時就需要對圖像進行標注。圖像標注是件很枯燥又很費人力物力的一件…

固件的完整形式是什么?

FW:前進 (FW: Forward) FW is an abbreviation of "Forward". FW是“ Forward”的縮寫 。 It is an expression, which is commonly used in Gmail or messaging platform. It is also written as FWD or Fwd or Fw. It shows that the email has been s…

[轉載] python __slots__ 詳解(上篇)

參考鏈接: Python的__name __(特殊變量) python中的new-style class要求繼承Python中的一個內建類型, 一般繼承object,也可以繼承list或者dict等其他的內建類型。 在python新式類中,可以定義一個變量__slots__,它的作…

委托BegionInvoke和窗體BegionInvoke

委托BegionInvoke是指通過委托方法執行多線程任務,例如: //定義委托成員變量 delegate void dg_DeleAirport(); //指定委托函數 dg_DeleAirport dga AirportBLL.DeleteHistoryTransAirport; //通過BeginInvoke以異步線程方式執行委托函數,可…

圖論 弦_混亂的弦

圖論 弦Problem statement: 問題陳述: You are provided an input string S and the string "includehelp". You need to figure out all possible subsequences "includehelp" in the string S? Find out the number of ways in which the s…

[轉載] Python列表操作

參考鏈接: Python中的基本運算符 Python列表: 序列是Python中最基本的數據結構。序列中的每個元素都分配一個數字 - 它的位置,或索引,第一個索引是0,第二個索引是1,依此類推; Python有6個序列的…

「原創」從馬云、馬化騰、李彥宏的對話,看出三人智慧差在哪里?

在今年中國IT領袖峰會上,馬云、馬化騰、李彥宏第一次單獨合影,同框畫面可以說很難得了。BAT關心的走勢一直是同行們競相捕捉的熱點,所以三位大Boss在這次大會上關于人工智能的見解,也受到廣泛關注與多方解讀。馬云認為機器比人聰明…

python 注釋含注釋_Python注釋

python 注釋含注釋Python注釋 (Python comments) Comments in Python are used to improve the readability of the code. It is useful information given by the programmer in source code for a better understanding of code and logic that they have used to solve the …

C2的完整形式是什么?

C2:核心2 (C2: Core 2) C2 is an abbreviation of "Core 2" or "Intel Core 2". C2是“ Core 2”或“ Intel Core 2”的縮寫 。 It is a family of Intels processor which was launched on the 27th of July, 2006. It comprises a series of…

scala特性_Scala | 特性應用

scala特性特性應用 (Trait App) Scala uses a trait called "App" which is used to convert objects into feasible programs. This conversion is done using the DelayedInit and the objects are inheriting the trait named App will be using this function. T…

[轉載] Python3中的表達式運算符

參考鏈接: Python中的除法運算符 1:Python常用表達式運算符 yield 生成器函數send協議 lambda args:expression 創建匿名函數 x if y else z 三元選擇表達式(當y為真時,x才會被計算) x or y 邏輯或(僅但x為假時y才會被計算) x and …

字符串矩陣轉換成長字符串_字符串矩陣

字符串矩陣轉換成長字符串Description: 描述: In this article, we are going to see how backtracking can be used to solve following problems? 在本文中,我們將看到如何使用回溯來解決以下問題? Problem statement: 問題陳述&#xf…

pythonchallenge_level2

level2 地址:http://www.pythonchallenge.com/pc/def/ocr.html。 源碼:gitcode.aliyun.com:qianlizhixing12/PythonChallenge.git。 問題:找出頁面源碼一點提示注釋中的稀有字符。 #!/usr/bin/env python3 # -*- coding:UTF-8 -*-# Level 2im…

[轉載] python類運算符的重載

參考鏈接: Python中的運算符重載 alist input().split() blist input().split() n float(input()) class Vector: def __init__(self, x0, y0, z0): # 請在此編寫你的代碼(可刪除pass語句) self.X x self.Y y self.Z z # 代碼結束 def __add__(self, other):…

r語言 運算符_R語言運算符

r語言 運算符R語言中的運算符 (Operators in R Language) Generally speaking, an operator is a symbol that gives proper commands to the compiler regarding a specific action to be executed. The operators are used for carrying out the mathematical or logical cal…

[轉載] Python基礎之類型轉換與算術運算符

參考鏈接: Python中的運算符函數| 1 一、注釋 1.注釋:對程序進行標注和說明,增加程序的可讀性。程序運行的時候會自動忽略注釋。 2.單行注釋:使用#的形式。但是#的形式只能注釋一行,如果有多行,就不方便…