+ 1
Why can't all languages have any type assigned to a variable
In pyhton if you have a variable you can assign any type to it, but in languages like c++, java, c# you can't do the same. Why?
4 Respostas
+ 4
This is a good thing!
Well, in C# you can *kind of* assign any type to a variable:
dynamic obj1 = new MyClass();
object obj2 = new MyClass2();
var obj3 = new MyClass3();
But anyway... The point is, that if in C# I write:
MyClass4 obj4 = new MyClass4();
and I then try to:
obj4.method_that_doesnt_exist();
The compiler will be able to catch this mistake, without you even needing to run the program. Python or Javascript don't do this for you, so you maybe only catch that when it's too late and the program crashes when you are doing something important.
We say python and js have "weak" type systems, and C# and Java have "strong" type systems. Usually, the stronger the type system, the more you can be sure that a program is correct once you run it.
+ 1
And - because I like talking about this stuff, an example. Say you have a method that only accepts prime numers as input. In python, you can throw any type anywhere, so it would look something like
def foo(n):
if(not (type(n) is int)):
raise Exception("this isnt even a number dummy")
if(not isPrime(n)):
raise Exception("this is not a prime number")
# do your stuff
C# has a stronger type system, so we could drop the "is number" check since the compiler can do that for us.
public int foo(int n){
if(!isPrime(n))
throw new ArgumentException("this is not a prime number");
// do your stuff
}
But we can do better - in extreme languages like Coq, you can even encode "primeness" into a number's type, so the compiler would notice any place you try to call foo with a non-prime and you can drop that isPrime check too!
+ 1
C++, Java, C#, etc. are compiled programming languages, those are more strict than scripts like python, javascript, ruby or php, which are interpreted and more flexible
0
actually c++11 introduced the auto type!
there you can just put anything you want, although you have to stick to the automatically detected and chosen data type.
why you need it then? for things like in my code example...
strict typing (as already mentioned) can prevent bugs, because you don't e.g. want to add accidentally an string to an integer.
friend of mine fixed around 50 potentially bugs by switching from JavaScript to TypeScript.
well you think differently if you work in medical field ;)
https://code.sololearn.com/cj90yG42bMB8/?ref=app