Overriding the Default Numeric Types
If you assign 1 to a variable, Scala assigns it the type Int :
scala> val a = 1
a: Int = 1
The following examples show one way to override simple numeric types:
scala> val a = 1d
a: Double = 1.0
scala> val a = 1f
a: Float = 1.0
scala> val a = 1000L
a: Long = 1000
Another approach is to annotate the variable with a type, like this:
scala> val a = 0: Byte
a: Byte = 0
scala> val a = 0: Int
a: Int = 0
scala> val a = 0: Short
a: Short = 0
scala> val a = 0: Double
a: Double = 0.0
scala> val a = 0: Float
a: Float = 0.0
Spacing after the colon isn’t important, so you can use this format, if preferred: val a = 0:Byte
According to the Scala Style Guide, those examples show the preferred style for annotating types, but personally I prefer the following syntax when assigning types to variables, specifying the type after the variable name:
scala> val a:Byte = 0
a: Byte = 0
scala> val a:Int = 0
a: Int = 0
You can create hex values by preceding the number with a leading 0x or 0X , and you can store them as an Int or Long :
scala> val a = 0x20
a: Int = 32
// if you want to store the value as a Long
scala> val a = 0x20L
a: Long = 32
It’s helpful to know about this approach when creating object instances. The general syntax looks like this:
// general case
var [name]:[Type] = [initial value]
// example
var a:Short = 0
This form can be helpful when you need to initialize numeric var fields in a class:
class Foo {
var a: Short = 0 // specify a default value
var b: Short = _ // defaults to 0
}
As shown, you can use the underscore character as a placeholder when assigning an initial value. This works when creating class variables, but doesn’t work in other places, such as inside a method. For numeric types this isn’t an issue - you can just assign the
type the value zero - but with most other types, you can use this approach inside a method:
var name = null.asInstanceOf[String]
Better yet, use the Option / Some / None pattern. It helps eliminate null values from your code, which is a very good thing. You’ll see this pattern used in the best Scala libraries and frameworks, such as the Play Framework.
Share this article with your friends.
No comments :
Post a Comment