I declared both the variables in two ways. But the output is same as "name". Then what is the difference between both the declarations? Are there any differences in memory allocations?
var x="name"
println(x)
var y:String="name"
println(y)
There is no difference with respect to memory allocations.
In case 1 Scala compiler infers the type for you
var x = "hello"
In case 2 You are explicitly announcing the type to guide the compiler
var x: String = "hello"
Explicit type declaration is important in some cases where Compiler inferred type is not good enough. For example
var a = 1
Compiler will infer the type of a as Int. But if I want a to be AnyVal in this case I have to say var a: AnyVal = 1
Related
How are they different? I get a bit confused because they seem to be similar concepts.
How does understanding them help with optimizing compilation time?
From Swift's own documentation:
Type Safety
Swift is a type-safe language. A type safe language encourages you to be clear about the types of values your code can work with. If part of your code expects a String, you can’t pass it an Int by mistake.
var welcomeMessage: String
welcomeMessage = 22 // this would create an error because you
//already specified that it's going to be a String
Type Inference
If you don’t specify the type of value you need, Swift uses type inference to work out the appropriate type. Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide.
var meaningOfLife = 42 // meaningOfLife is inferred to be of type Int
meaningOfLife = 55 // it Works, because 55 is an Int
Type Safety & Type Inference together
var meaningOfLife = 42 // 'Type inference' happened here, we didn't specify that this an Int, the compiler itself found out.
meaningOfLife = 55 // it Works, because 55 is an Int
meaningOfLife = "SomeString" // Because of 'Type Safety' ability you will get an
//error message: 'cannot assign value of type 'String' to type 'Int''
Tricky example for protocols with associated types:
Imagine the following protocol
protocol Identifiable {
associatedtype ID
var id: ID { get set }
}
You would adopt it like this:
struct Person: Identifiable {
typealias ID = String
var id: String
}
However you can also adopt it like this:
struct Website: Identifiable {
var id: URL
}
You can remove the typealias. The compiler will still infer the type.
For more see Generics - Associated Types
Thanks to Swift’s type inference, you don’t actually need to declare a
concrete Item of Int as part of the definition of IntStack. Because
IntStack conforms to all of the requirements of the Container
protocol, Swift can infer the appropriate Item to use, simply by
looking at the type of the append(_:) method’s item parameter and the
return type of the subscript. Indeed, if you delete the typealias Item
= Int line from the code above, everything still works, because it’s clear what type should be used for Item.
Type-safety and Generics
Suppose you have the following code:
struct Helper<T: Numeric> {
func adder(_ num1: T, _ num2: T) -> T {
return num1 + num2
}
var num: T
}
T can be anything that's numeric e.g. Int, Double, Int64, etc.
However as soon as you type let h = Helper(num: 10) the compiler will assume that T is an Int. It won't accept Double, Int64, for its adder func anymore. It will only accept Int.
This is again because of type-inference and type-safety.
type-inference: because it has to infer that that the generic is of type Int.
type-safety: because once the T is set to be of type Int, it will no longer accept Int64, Double...
As you can see in the screenshot the signature is now changed to only accept a parameter of type Int
Pro tip to optimize compiler performance:
The less type inference your code has to do the faster it compiles. Hence it's recommended to avoid collection literals. And the longer a collection gets, the slower its type inference becomes...
not bad
let names = ["John", "Ali", "Jane", " Taika"]
good
let names : [String] = ["John", "Ali", "Jane", " Taika"]
For more see this answer.
Also see Why is Swift compile time so slow?
The solution helped his compilation time go down from 10/15 seconds to a single second.
I am confused with following initialization
var in = None: Option[FileInputStream]
however what I know is that
var varName : type = _ // default value initialization
var varName : type = someValue // other than default intitalization
but what is
var in = None: Option[FileInputStream]
Please help
Thanks
This is called a type ascription and the resulting expression is called a typed expression. It, well, ascribes a type to an expression:
expr: Type
means "treat expr as if it had Type".
For example:
1
// Int
1: Float
// Float
Obviously, the expression needs to conform to the type that is ascribed to it.
The most widely used example of type ascription is probably the _* pseudo-type, which unpacks a Seq into a series of arguments:
def sumNums(nums: Int*) = nums.sum
sumNums()
//=> 0
sumNums(1)
//=> 1
sumNums(1, 2)
//=> 3
sumNums(Seq(1, 2))
// error: type mismatch;
// found : Seq[Int]
// required: Int
// sumNums(Seq(1, 2))
// ^
sumNums(Seq(1, 2): _*)
//=> 3
In your particular case, I find it questionable to ascribe a type to an expression just to get the type inferencer to infer the correct type, when you could just as well have declared the correct type to begin with:
var in: Option[FileInputStream] = None
With regards to your comments:
however what I know is that
var varName : type = _ // default value initialization
var varName : type = someValue // other than default intitalization
You can also leave out the type:
var varName = someValue
In this case, the type is inferred from the expression someValue.
var varName = _
Obviously, this cannot work: the type is inferred from the expression, but the value of the expression is inferred from the type. Therefore, this is not allowed.
Your example uses the form with inferred type:
var in = someExpression
So, the type of in is inferred from the type of someExpression.
Now, if we said
var in = None
then the type inferred for in would be None.type, i.e. the singleton type of the None object. But that doesn't make sense: why would we have a var, i.e. a variable which we can change, when we then give it a singleton type, i.e. an type which has only a single instance. So, we can re-assign in as often as we want, but we can only assign the same thing to it. That's illogical. (Well, technically, we could also assign null to it.)
And in fact, we want to be able to assign something to it, but also know whether we assigned something to it or not. That's why we use an Option in this case, and initialize it with None. So, re-interpret None as an Option, so that Scala infers the correct type:
var in = None: Option[FileInputStream]
// [name] = [value] : [type]
var in = None : Option[FileInputStream]
// can equivalently be written as:
var in: Option[FileInputStream] = None
This creates a variable of type Option[FileInputStream], with the initial value None.
To learn more about Scala's Option type, see http://www.scala-lang.org/api/current/#scala.Option
How are they different? I get a bit confused because they seem to be similar concepts.
How does understanding them help with optimizing compilation time?
From Swift's own documentation:
Type Safety
Swift is a type-safe language. A type safe language encourages you to be clear about the types of values your code can work with. If part of your code expects a String, you can’t pass it an Int by mistake.
var welcomeMessage: String
welcomeMessage = 22 // this would create an error because you
//already specified that it's going to be a String
Type Inference
If you don’t specify the type of value you need, Swift uses type inference to work out the appropriate type. Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide.
var meaningOfLife = 42 // meaningOfLife is inferred to be of type Int
meaningOfLife = 55 // it Works, because 55 is an Int
Type Safety & Type Inference together
var meaningOfLife = 42 // 'Type inference' happened here, we didn't specify that this an Int, the compiler itself found out.
meaningOfLife = 55 // it Works, because 55 is an Int
meaningOfLife = "SomeString" // Because of 'Type Safety' ability you will get an
//error message: 'cannot assign value of type 'String' to type 'Int''
Tricky example for protocols with associated types:
Imagine the following protocol
protocol Identifiable {
associatedtype ID
var id: ID { get set }
}
You would adopt it like this:
struct Person: Identifiable {
typealias ID = String
var id: String
}
However you can also adopt it like this:
struct Website: Identifiable {
var id: URL
}
You can remove the typealias. The compiler will still infer the type.
For more see Generics - Associated Types
Thanks to Swift’s type inference, you don’t actually need to declare a
concrete Item of Int as part of the definition of IntStack. Because
IntStack conforms to all of the requirements of the Container
protocol, Swift can infer the appropriate Item to use, simply by
looking at the type of the append(_:) method’s item parameter and the
return type of the subscript. Indeed, if you delete the typealias Item
= Int line from the code above, everything still works, because it’s clear what type should be used for Item.
Type-safety and Generics
Suppose you have the following code:
struct Helper<T: Numeric> {
func adder(_ num1: T, _ num2: T) -> T {
return num1 + num2
}
var num: T
}
T can be anything that's numeric e.g. Int, Double, Int64, etc.
However as soon as you type let h = Helper(num: 10) the compiler will assume that T is an Int. It won't accept Double, Int64, for its adder func anymore. It will only accept Int.
This is again because of type-inference and type-safety.
type-inference: because it has to infer that that the generic is of type Int.
type-safety: because once the T is set to be of type Int, it will no longer accept Int64, Double...
As you can see in the screenshot the signature is now changed to only accept a parameter of type Int
Pro tip to optimize compiler performance:
The less type inference your code has to do the faster it compiles. Hence it's recommended to avoid collection literals. And the longer a collection gets, the slower its type inference becomes...
not bad
let names = ["John", "Ali", "Jane", " Taika"]
good
let names : [String] = ["John", "Ali", "Jane", " Taika"]
For more see this answer.
Also see Why is Swift compile time so slow?
The solution helped his compilation time go down from 10/15 seconds to a single second.
I'm new to Swift and I am confused about the following:
In the lines Int(something) and var x :Int = something, what is the difference between Int() and :Int?
In fact var x = Int(something) and var x : Int = something is exactly the same.
Unlike in Objective-C where int is a scalar type Int in Swift ist a struct and
structs must be initialized.
The former syntax is an explicit call of the initializer, the latter an implicit call by assigning the value
From a pure language perspective, the correct way to assign a value to an integer (or other numerical types) variable is:
let num = Int(16)
or any of its variants.
However Swift implements some syntactic sugar to make that less verbose - thanks to which you can rewrite the above statement as:
let num = 16
which is equivalent to:
let num: Int = 16
(thanks to type inference)
This is possible because the Int type implements the IntegerLiteralConvertible protocol, and by doing that the compiler is able to translate an integer literal into an initializer invocation.
There are several other protocols like that, for string, array, float, etc.
If you want to know more, I recommend reading Swift Literal Convertibles at NSHipster.
If you are wondering if you can do that on your own classes/structs, the answer is yes - you just have to implement the protocol corresponding to the literal type you want to use.
In Swift, constants can expressed with let keyword like this
let MyConstant = 100
and explicitly defined with type name like below
let MyConstant: Int = 100
what are the benefit of using second method?
In case the compiler can't figure out the type of the rhs, for example,
let x: Double = 1
Sometimes, the type inference will infer types that is less abstract than what you want. If you want your identifier to be less abstract, you can explicitly define the type of your identifiers.
For example (assume that return type of obj.getString() is NSString:
let someObject: NSObject = obj.getString()
let someString = obj.getString()
On the second line, the constant someString will have type of NSString, whereas the on the first line it will be what you explicitly defined.
If the type definition is omitted, its type is inferred, which for integer literals are inferred as Int, so in this case both statements are exactly the same.
Specifying the type in this case doesn't increase readability and just adds unnecessary noise since the type is clearly an Integer, but in cases where it's not obvious what the type is, e.g:
let MyConstant : Int = createNumber()
Then there's an argument for explicitly specifying the type info for the additional clarity.
Imagine you want to set a floating point value for amount.
And if you define it this way :
let MyConstant = 100
your constant will be treated as INT instead of floating point one , So you have to implicity define type or provide a value that will help compiler infer the type of constant. e.g We have two options
here
Case A
let MyConstant = 100.0
Case B
let MyConstant:Double = 100
If you are writing code for others and want it to be more expressive and readable the second approach is much better,bcz it shows the intent of program not just for compiler, but also for the coder.