Generics and casting – cannot cast inherited class to base class

RepositoryBase<EntityBase> is not a base class of MyEntityRepository. You’re looking for generic variance which exists in C# to a limited extent, but wouldn’t apply here. Suppose your RepositoryBase<T> class had a method like this: void Add(T entity) { … } Now consider: MyEntityRepository myEntityRepo = GetMyEntityRepo(); // whatever RepositoryBase<EntityBase> baseRepo = (RepositoryBase<EntityBase>)myEntityRepo; baseRepo.Add(new OtherEntity(…)); Now … Read more

java.lang.Integer cannot be cast to java.lang.Long

Both Integer and Long are subclasses of Number, so I suspect you can use: long ipInt = ((Number) obj.get(“ipInt”)).longValue(); That should work whether the value returned by obj.get(“ipInt”) is an Integer reference or a Long reference. It has the downside that it will also silently continue if ipInt has been specified as a floating point … Read more

Compilation error: Smart cast to ” is impossible, because ” is a local variable that is captured by a changing closure

In general, when a mutable variable is captured in a lambda function closure, smart casts are not applicable to that variable, both inside the lambda and in the declaring scope after the lambda was created. It’s because the function may escape from its enclosing scope and may be executed later in a different context, possibly … Read more

Python: Test if value can be converted to an int in a list comprehension

If you only deal with integers, you can use str.isdigit(): Return true if all characters in the string are digits and there is at least one character, false otherwise. [row for row in listOfLists if row[x].isdigit()] Or if negative integers are possible (but should be allowed): row[x].lstrip(‘-‘).isdigit() And of course this all works only if … Read more

What exactly is a type cast in C/C++?

A type cast is basically a conversion from one type to another. It can be implicit (i.e., done automatically by the compiler, perhaps losing info in the process) or explicit (i.e., specified by the developer in the code). The space occupied by the types is of secondary importance. More important is the applicability (and sometimes … Read more

Why use static_cast(x) instead of (T)x?

The main reason is that classic C casts make no distinction between what we call static_cast<>(), reinterpret_cast<>(), const_cast<>(), and dynamic_cast<>(). These four things are completely different. A static_cast<>() is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it’s a bit risky is … Read more