Table of Contents
- Introduction to Type Casting
- Implicit vs Explicit Type Conversion
- Type Casting in Different Languages
- Primitive Type Casting
- Object Type Casting
- String Conversion
- Type Conversion Functions
- Type Coercion
- Safe Type Casting
- Common Pitfalls
- Best Practices
- Real-World Examples
Introduction to Type Casting
Type casting (or type conversion) is the process of converting a value from one data type to another. It's a fundamental concept in programming that allows you to work with different types of data effectively.
What is Type Casting?
# Type casting examples in Python integer_value = 10 float_value = float(integer_value) # 10.0 string_value = str(integer_value) # "10"
// Type casting examples in JavaScript let number = 42; let string = String(number); // "42" let boolean = Boolean(number); // true
Why Type Casting Matters
Type Casting Importance: ├── Data Compatibility - Convert between types for operations ├── Input Validation - Convert user input to proper types ├── API Integration - Format data for external services ├── Memory Management - Choose appropriate size types ├── Precision Control - Handle floating-point operations └── Type Safety - Ensure correct data types in strongly-typed languages
Implicit vs Explicit Type Conversion
Implicit Type Conversion (Type Coercion)
The compiler or interpreter automatically converts types without explicit instruction.
# Python - Implicit conversion integer = 10 float_num = 3.14 result = integer + float_num # int → float automatically print(type(result)) # <class 'float'> # Boolean to integer true_value = True false_value = False print(true_value + 5) # 6 (True → 1) print(false_value + 5) # 5 (False → 0)
// JavaScript - Implicit conversion (coercion) let x = 5; let y = "10"; let result = x + y; // "510" (number → string) console.log(result); let a = "5"; let b = "10"; let sum = a + b; // "510" (string concatenation) let comparison = "5" == 5; // true (string → number)
Explicit Type Conversion (Type Casting)
The programmer explicitly converts values using casting functions or operators.
# Python - Explicit conversion num_str = "123" num_int = int(num_str) # String → Integer num_float = float(num_str) # String → Float # Converting between number types a = 10 b = float(a) # 10.0 c = int(3.14) # 3 (truncates decimal) # Complex conversions hex_value = hex(255) # "0xff" binary_value = bin(42) # "0b101010"
// Java - Explicit conversion String numStr = "456"; int numInt = Integer.parseInt(numStr); // String → int double numDouble = Double.parseDouble(numStr); // String → double // Casting between numeric types int x = 10; double y = (double) x; // 10.0 double z = 3.14; int w = (int) z; // 3 (truncates)
Comparison Table
| Aspect | Implicit | Explicit |
|---|---|---|
| Control | Automatic | Programmer-controlled |
| Safety | Can be dangerous | Safer when done properly |
| Readability | Can be confusing | Clear intent |
| Performance | No overhead | Minimal overhead |
| Languages | JavaScript, PHP | C, Java, Python, etc. |
Type Casting in Different Languages
Python Type Casting
# Python type casting functions
# Numbers
int_val = int("123") # String to integer
float_val = float(123) # Integer to float
complex_val = complex(10) # Integer to complex
# Strings
str_val = str(456) # Number to string
str_bool = str(True) # Boolean to string
# Boolean
bool_val = bool(0) # Integer to boolean (False)
bool_val = bool(42) # True
bool_val = bool("") # False (empty string)
bool_val = bool("Hello") # True
# Lists and tuples
list_val = list("abc") # String to list: ['a', 'b', 'c']
tuple_val = tuple([1, 2, 3]) # List to tuple: (1, 2, 3)
JavaScript Type Casting
// JavaScript type casting methods
// String conversion
String(123); // "123"
String(true); // "true"
(123).toString(); // "123"
// Number conversion
Number("456"); // 456
Number("123abc"); // NaN
parseInt("42px"); // 42
parseFloat("3.14"); // 3.14
+"123"; // 123 (unary plus)
// Boolean conversion
Boolean(0); // false
Boolean(""); // false
Boolean(null); // false
Boolean(42); // true
Boolean("Hello"); // true
!!42; // true (double NOT)
Java Type Casting
// Java type casting // Primitive casting int num = 100; long longNum = num; // Implicit widening short shortNum = (short) num; // Explicit narrowing (may lose data) // Object casting String str = "123"; Integer intObj = Integer.parseInt(str); int primitive = intObj; // Auto-unboxing // Wrapper classes Integer wrapped = Integer.valueOf(100); String strVal = wrapped.toString();
C/C++ Type Casting
// C type casting int a = 10; float b = (float)a; // C-style cast double c = 3.14159; int d = (int)c; // Truncates to 3 // C++ casting operators int x = 42; double y = static_cast<double>(x); // C++ style float z = 3.14f; int w = static_cast<int>(z); // 3 // Reinterpret cast (dangerous) int* ptr = &x; void* voidPtr = reinterpret_cast<void*>(ptr);
PHP Type Casting
<?php // PHP type casting $str = "123"; $int = (int)$str; // 123 $float = (float)$str; // 123.0 $bool = (bool)$str; // true // Settype function $value = "456"; settype($value, "int"); // $value becomes 456 // Type juggling (implicit) $result = "5" + "10"; // 15 (string to int) $concat = "5" . "10"; // "510" (string concatenation) ?>
Primitive Type Casting
Numeric Conversions
# Python - Numeric conversions
# Integer to Float
int_num = 42
float_num = float(int_num) # 42.0
float_num = int_num * 1.0 # 42.0
# Float to Integer (truncation)
float_num = 3.14159
int_num = int(float_num) # 3 (truncates)
int_num = round(float_num) # 3 (rounds)
int_num = math.floor(3.9) # 3 (floor)
int_num = math.ceil(3.1) # 4 (ceiling)
# Integer to Complex
complex_num = complex(10, 20) # (10+20j)
# String to Number
valid_int = int("42")
valid_float = float("3.14")
# invalid_int = int("abc") # ValueError
Handling Precision Loss
# Precision loss examples
large_int = 2**53 + 1
float_converted = float(large_int) # May lose precision
print(f"Original: {large_int}")
print(f"Converted: {int(float_converted)}")
# Better ways to handle large numbers
from decimal import Decimal
decimal_val = Decimal("12345678901234567890.1234567890")
float_val = float(decimal_val) # Still loses precision
Integer Size Considerations
# Python - Arbitrary precision (no overflow)
huge_number = 10**100
print(huge_number) # Works fine
# But conversions to other types have limits
try:
float_huge = float(huge_number) # OverflowError
except OverflowError as e:
print(f"Error: {e}")
// C - Fixed-size integers
#include <stdint.h>
uint8_t small = 255;
uint16_t medium = small; // Fine
uint8_t overflow = (uint8_t)256; // Overflow: becomes 0
// Check before casting
int large = 50000;
if (large <= UINT16_MAX) {
uint16_t safe = (uint16_t)large;
}
Object Type Casting
Inheritance and Polymorphism
# Python - Object casting class Animal: def speak(self): return "Some sound" class Dog(Animal): def speak(self): return "Woof!" def fetch(self): return "Fetching..." class Cat(Animal): def speak(self): return "Meow!" # Upcasting (implicit - always safe) animal = Dog() # Dog object as Animal print(animal.speak()) # "Woof!" # Downcasting (explicit - may be unsafe) animal = Animal() if isinstance(animal, Dog): dog = animal # Only works if animal is Dog print(dog.fetch())
// Java - Object casting
class Animal {
public void speak() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
public void speak() {
System.out.println("Woof!");
}
public void fetch() {
System.out.println("Fetching...");
}
}
// Usage
Animal animal = new Dog();
animal.speak(); // "Woof!"
// Downcasting with instanceof check
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.fetch(); // Works
}
Interface Casting
# Python - Duck typing (no explicit interface casting)
class FileReader:
def read(self):
return "Reading file"
class DatabaseReader:
def read(self):
return "Querying database"
def process_data(reader):
# Any object with read() method works
data = reader.read()
print(f"Processing: {data}")
process_data(FileReader())
process_data(DatabaseReader())
// Java - Interface casting
interface Readable {
void read();
}
class FileReader implements Readable {
public void read() {
System.out.println("Reading file");
}
public void close() {
System.out.println("Closing file");
}
}
// Usage
Readable reader = new FileReader();
reader.read(); // Works
// reader.close(); // Compile error - not in interface
if (reader instanceof FileReader) {
FileReader fileReader = (FileReader) reader;
fileReader.close(); // Works
}
String Conversion
Converting Numbers to Strings
# Python - Number to string
num = 123
str1 = str(num) # "123"
str2 = format(num, "d") # "123"
str3 = f"{num}" # "123"
str4 = "%d" % num # "123"
# Formatting with precision
pi = 3.14159
str_pi = f"{pi:.2f}" # "3.14"
str_pi = format(pi, ".2f") # "3.14"
# Hexadecimal, binary, octal
hex_str = hex(255) # "0xff"
bin_str = bin(42) # "0b101010"
oct_str = oct(64) # "0o100"
// JavaScript - Number to string
let num = 123;
let str1 = String(num); // "123"
let str2 = num.toString(); // "123"
let str3 = num + ""; // "123" (implicit)
let str4 = `${num}`; // "123"
// Formatting
let pi = 3.14159;
let formatted = pi.toFixed(2); // "3.14"
let scientific = pi.toExponential(2); // "3.14e+0"
// Radix conversion
let hex = num.toString(16); // "7b"
let binary = num.toString(2); // "1111011"
Converting Strings to Numbers
# Python - String to number
int_str = "123"
float_str = "3.14"
hex_str = "0xff"
# Basic conversion
int_val = int(int_str) # 123
float_val = float(float_str) # 3.14
hex_val = int(hex_str, 16) # 255
# Handling invalid input
try:
invalid = int("abc")
except ValueError:
print("Cannot convert")
# Using regex for validation
import re
def safe_int_convert(value):
if re.match(r'^-?\d+$', value):
return int(value)
return None
// JavaScript - String to number
let intStr = "123";
let floatStr = "3.14";
let num1 = Number(intStr); // 123
let num2 = parseInt(intStr); // 123
let num3 = parseFloat(floatStr); // 3.14
let num4 = +intStr; // 123 (unary plus)
// Handling non-numeric
let invalid = parseInt("123abc"); // 123 (stops at first non-digit)
let nan = Number("abc"); // NaN
// Safe conversion
function safeParseInt(str) {
let num = parseInt(str, 10);
if (isNaN(num)) {
return null;
}
return num;
}
Type Conversion Functions
Built-in Conversion Functions
# Python built-in conversions # Numeric conversions int() float() complex() bin() # to binary string oct() # to octal string hex() # to hexadecimal string # String conversions str() repr() # developer-friendly string ascii() # ASCII-only representation # Collection conversions list() tuple() set() dict() frozenset() # Boolean conversion bool() # Character/byte conversions chr() # integer to character ord() # character to integer bytes() # to bytes bytearray()
Custom Type Converters
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def to_fahrenheit(self):
return (self.celsius * 9/5) + 32
def to_kelvin(self):
return self.celsius + 273.15
# String representation
def __str__(self):
return f"{self.celsius}°C"
def __repr__(self):
return f"Temperature({self.celsius})"
# Numeric conversion
def __int__(self):
return int(self.celsius)
def __float__(self):
return float(self.celsius)
# Usage
temp = Temperature(25)
print(str(temp)) # "25°C"
print(repr(temp)) # "Temperature(25)"
print(int(temp)) # 25
print(float(temp)) # 25.0
print(temp.to_fahrenheit()) # 77.0
Static Methods for Conversion
class DataConverter:
@staticmethod
def to_int(value, default=0):
"""Safely convert to integer"""
try:
return int(value)
except (ValueError, TypeError):
return default
@staticmethod
def to_float(value, default=0.0):
"""Safely convert to float"""
try:
return float(value)
except (ValueError, TypeError):
return default
@staticmethod
def to_bool(value):
"""Convert various types to boolean"""
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return value != 0
if isinstance(value, str):
return value.lower() in ('true', 'yes', '1', 'on')
return bool(value)
# Usage
print(DataConverter.to_int("123")) # 123
print(DataConverter.to_int("abc", -1)) # -1
print(DataConverter.to_bool("yes")) # True
print(DataConverter.to_bool(0)) # False
Type Coercion
Understanding Coercion
Type coercion is the automatic conversion of values from one type to another during operations.
# Python - Limited coercion # Numbers result1 = 5 + 3.14 # 8.14 (int → float) result2 = 10 + True # 11 (True → 1) result3 = "5" + "10" # "510" (string concatenation) # result4 = "5" + 10 # TypeError in Python # Comparisons print(5 == 5.0) # True (float converted for comparison) print(True == 1) # True print(False == 0) # True
// JavaScript - Extensive coercion
// Addition operator
console.log(5 + "5"); // "55" (number → string)
console.log("5" + 5); // "55" (number → string)
console.log(5 + true); // 6 (true → 1)
console.log("5" + true); // "5true" (boolean → string)
// Subtraction operator (forces numeric)
console.log("10" - 5); // 5 (string → number)
console.log("10" - "5"); // 5 (both to numbers)
console.log("abc" - 5); // NaN
// Comparison operators
console.log("5" == 5); // true (coercion)
console.log("5" === 5); // false (strict, no coercion)
console.log("" == 0); // true
console.log("" == false); // true
Coercion in Different Languages
# Python - Strict typing
# Most operations require explicit conversion
age_input = input("Age: ") # Returns string
age = int(age_input) # Must convert explicitly
// JavaScript - Loose typing
let age = prompt("Age: "); // Returns string
let nextAge = age + 1; // "251" (string concatenation)
let correctedAge = Number(age) + 1; // Must be explicit
// Java - Strong typing String ageStr = "25"; int age = Integer.parseInt(ageStr); // Must convert int nextAge = age + 1; // Fine after conversion
Safe Type Casting
Try-Catch for Safe Conversion
def safe_convert(value, target_type):
"""Safely convert value to target type"""
try:
if target_type == int:
return int(value)
elif target_type == float:
return float(value)
elif target_type == bool:
return bool(value)
elif target_type == str:
return str(value)
else:
raise ValueError(f"Unsupported type: {target_type}")
except (ValueError, TypeError) as e:
print(f"Conversion error: {e}")
return None
# Usage
print(safe_convert("123", int)) # 123
print(safe_convert("abc", int)) # None (with error message)
print(safe_convert("3.14", float)) # 3.14
Type Checking Before Casting
def safe_cast(value, to_type):
"""Type-safe casting with validation"""
if value is None:
return None
# Check if value can be converted
if to_type in (int, float):
if isinstance(value, (int, float)):
return to_type(value)
if isinstance(value, str) and value.strip().lstrip('-').isdigit():
return to_type(value)
if to_type == bool:
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return value != 0
if isinstance(value, str):
return value.lower() in ('true', 'yes', '1', 'on')
return None
Using Typing Module
from typing import Union, Optional, TypeVar
import numbers
T = TypeVar('T')
def safe_cast_typed(value: Union[str, int, float],
target_type: type[T]) -> Optional[T]:
"""
Type-safe conversion with error handling
"""
try:
if target_type == int:
if isinstance(value, numbers.Integral):
return value
if isinstance(value, str):
return int(value.strip())
elif target_type == float:
if isinstance(value, numbers.Number):
return float(value)
if isinstance(value, str):
return float(value.strip())
elif target_type == str:
return str(value)
except (ValueError, TypeError):
return None
return None
Common Pitfalls
1. Loss of Precision
# Loss of precision in float to int conversion float_value = 3.999999999999999 int_value = int(float_value) # 3 (not 4) # Better: use rounding rounded = round(3.999999999999999) # 4 # Float comparison issues a = 0.1 + 0.2 b = 0.3 print(a == b) # False! Use math.isclose()
2. Unexpected Boolean Conversions
# Python - Boolean conversion surprises
print(bool("False")) # True (non-empty string)
print(bool(0)) # False
print(bool("0")) # True (non-empty string)
print(bool([])) # False (empty list)
print(bool([0])) # True (non-empty list)
# Safe boolean conversion for strings
def safe_bool(value):
if isinstance(value, str):
return value.lower() in ('true', 'yes', '1')
return bool(value)
3. Integer Overflow (C/Java)
// C - Integer overflow
#include <stdio.h>
#include <limits.h>
int main() {
int max = INT_MAX; // 2,147,483,647
int overflow = max + 1; // -2,147,483,648 (wraps around)
printf("%d\n", overflow);
return 0;
}
4. Type Coercion Confusion
// JavaScript - Coercion pitfalls
console.log([] + []); // "" (empty string)
console.log([] + {}); // "[object Object]"
console.log({} + []); // "[object Object]"
console.log("5" - "3"); // 2 (works)
console.log("5" + "3"); // "53" (not 8)
console.log(1 < 2 < 3); // true? Actually: (1 < 2) = true → 1 < 3 = true
console.log(3 > 2 > 1); // false? (3 > 2) = true → 1 > 1 = false
5. NaN Handling
// JavaScript - NaN behavior
console.log(parseInt("abc")); // NaN
console.log(NaN == NaN); // false
console.log(isNaN("123")); // false
console.log(Number.isNaN("123")); // false (stricter)
// Safe check
function isReallyNaN(value) {
return typeof value === 'number' && isNaN(value);
}
Best Practices
1. Always Validate Before Casting
def safe_parse_int(value):
"""Parse integer with validation"""
if isinstance(value, int):
return value
if isinstance(value, str):
value = value.strip()
if value and (value.lstrip('-')).isdigit():
return int(value)
raise ValueError(f"Cannot convert {value} to int")
2. Use Type Hints (Python)
from typing import Union, Optional
def process_value(value: Union[str, int, float]) -> Optional[int]:
"""
Process value with explicit type handling
"""
try:
if isinstance(value, str):
return int(value.strip())
elif isinstance(value, (int, float)):
return int(value)
else:
raise TypeError(f"Unsupported type: {type(value)}")
except (ValueError, TypeError):
return None
3. Use Explicit Conversion Functions
class TypeConverter:
"""Centralized type conversion utilities"""
@staticmethod
def to_int(value, default=0):
try:
return int(value)
except (ValueError, TypeError):
return default
@staticmethod
def to_float(value, default=0.0):
try:
return float(value)
except (ValueError, TypeError):
return default
@staticmethod
def to_str(value, default=""):
if value is None:
return default
return str(value)
@staticmethod
def to_bool(value, default=False):
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return value != 0
if isinstance(value, str):
return value.lower() in ('true', 'yes', '1', 'on')
return default
4. Handle Edge Cases Explicitly
def robust_cast(value, target_type, default=None):
"""Robust casting with explicit edge case handling"""
# Handle None
if value is None:
return default
# Handle empty strings
if isinstance(value, str) and value.strip() == "":
return default
# Special handling for boolean
if target_type == bool:
if isinstance(value, str):
if value.lower() in ('true', 'yes', '1', 'on'):
return True
if value.lower() in ('false', 'no', '0', 'off'):
return False
return default
return bool(value)
try:
return target_type(value)
except (ValueError, TypeError):
return default
# Usage
print(robust_cast("", int, 0)) # 0
print(robust_cast("yes", bool, False)) # True
print(robust_cast(None, int)) # None
5. Use Type-Safe APIs
# Define clear interfaces
class DataValidator:
@staticmethod
def validate_and_convert(data: dict) -> dict:
"""Validate and convert data with type safety"""
result = {}
# Integer fields
if 'age' in data:
age = data['age']
if isinstance(age, str) and age.isdigit():
result['age'] = int(age)
elif isinstance(age, int):
result['age'] = age
# Float fields
if 'salary' in data:
try:
result['salary'] = float(data['salary'])
except (ValueError, TypeError):
result['salary'] = 0.0
# Boolean fields
if 'active' in data:
active = data['active']
if isinstance(active, str):
result['active'] = active.lower() in ('true', 'yes', '1')
else:
result['active'] = bool(active)
return result
6. Document Type Expectations
def process_user_data(user_id: Union[int, str],
name: str,
age: Optional[Union[int, str]] = None) -> dict:
"""
Process user data with explicit type expectations.
Args:
user_id: Can be integer or string (will be converted to int)
name: Must be a string
age: Optional, can be integer or string (will be converted)
Returns:
Dictionary with properly typed user data
Raises:
ValueError: If conversion fails for required fields
"""
# Convert user_id to int
try:
user_id_int = int(user_id)
except (ValueError, TypeError):
raise ValueError(f"Invalid user_id: {user_id}")
# Validate name
if not isinstance(name, str) or not name.strip():
raise ValueError("Name is required and must be a non-empty string")
# Convert age if provided
age_int = None
if age is not None:
try:
age_int = int(age)
if age_int < 0 or age_int > 150:
raise ValueError("Age must be between 0 and 150")
except (ValueError, TypeError):
raise ValueError(f"Invalid age: {age}")
return {
'user_id': user_id_int,
'name': name.strip(),
'age': age_int
}
Real-World Examples
Example 1: Form Data Processing
class FormProcessor:
"""Process and validate form data with type conversion"""
def __init__(self, data):
self.raw_data = data
self.processed_data = {}
self.errors = []
def process_field(self, field, converter, required=False, default=None):
"""Process a single form field"""
value = self.raw_data.get(field)
if value is None or value == "":
if required:
self.errors.append(f"{field} is required")
return None
return default
try:
return converter(value)
except (ValueError, TypeError):
self.errors.append(f"Invalid {field}: {value}")
return None
def process_form(self):
"""Process complete form"""
self.processed_data['name'] = self.process_field(
'name', str, required=True
)
self.processed_data['age'] = self.process_field(
'age', int, required=True
)
self.processed_data['salary'] = self.process_field(
'salary', float, default=0.0
)
self.processed_data['is_active'] = self.process_field(
'active',
lambda x: str(x).lower() in ('true', 'yes', '1', 'on'),
default=False
)
return self.processed_data, self.errors
# Usage
form_data = {
'name': 'John Doe',
'age': '30',
'salary': '50000.50',
'active': 'yes'
}
processor = FormProcessor(form_data)
data, errors = processor.process_form()
if errors:
print(f"Errors: {errors}")
else:
print(f"Processed: {data}")
Example 2: API Response Parsing
import json
from typing import Any, Dict, List, Optional
class APIParser:
"""Parse and convert API responses"""
@staticmethod
def parse_user(user_data: Dict[str, Any]) -> Dict[str, Any]:
"""Parse user object from API"""
return {
'id': int(user_data.get('id', 0)),
'name': str(user_data.get('name', '')),
'email': str(user_data.get('email', '')),
'age': APIParser._safe_int(user_data.get('age')),
'is_verified': bool(user_data.get('verified', False))
}
@staticmethod
def _safe_int(value: Any, default: int = 0) -> int:
"""Safely convert to int"""
try:
if isinstance(value, str):
# Remove non-digit characters
cleaned = ''.join(filter(str.isdigit, value))
return int(cleaned) if cleaned else default
return int(value)
except (ValueError, TypeError):
return default
@staticmethod
def parse_response(response: str) -> Optional[List[Dict[str, Any]]]:
"""Parse JSON response and convert types"""
try:
data = json.loads(response)
if isinstance(data, list):
return [APIParser.parse_user(item) for item in data]
elif isinstance(data, dict):
return [APIParser.parse_user(data)]
return []
except json.JSONDecodeError:
return None
# Usage
api_response = '[{"id": "123", "name": "Alice", "age": "25", "verified": "true"}]'
users = APIParser.parse_response(api_response)
print(users)
Example 3: Database Query Results
class DatabaseRow:
"""Convert database row to typed Python objects"""
def __init__(self, row: tuple, schema: Dict[str, type]):
self.row = row
self.schema = schema
self.data = {}
self._convert()
def _convert(self):
"""Convert tuple to typed dictionary"""
for i, (key, type_) in enumerate(self.schema.items()):
value = self.row[i] if i < len(self.row) else None
if value is None:
self.data[key] = None
continue
try:
if type_ == int:
self.data[key] = int(value)
elif type_ == float:
self.data[key] = float(value)
elif type_ == bool:
self.data[key] = bool(value) if value not in ('0', 'false') else False
elif type_ == str:
self.data[key] = str(value)
else:
self.data[key] = value
except (ValueError, TypeError):
self.data[key] = None
def get(self, key: str, default=None):
"""Get typed value by key"""
return self.data.get(key, default)
def __getitem__(self, key: str):
return self.data[key]
def __repr__(self):
return str(self.data)
# Usage
schema = {
'id': int,
'name': str,
'age': int,
'salary': float,
'active': bool
}
# Simulate database row
row = (1, 'John Doe', '30', '55000.50', '1')
parsed = DatabaseRow(row, schema)
print(parsed.get('name')) # "John Doe"
print(parsed['salary']) # 55000.5
print(parsed['active']) # True
Conclusion
Key Takeaways
- Type casting is essential for working with different data types
- Implicit vs explicit casting affects code clarity and safety
- Always validate before casting, especially with user input
- Be aware of language-specific coercion rules and pitfalls
- Use appropriate tools for safe conversion:
- Try-catch blocks
- Validation functions
- Type checking
- Unit tests
Type Casting Best Practices
Do: ├── Always validate before casting ├── Use explicit casting for clarity ├── Handle edge cases (None, empty strings, etc.) ├── Document type expectations ├── Use language-specific type checking ├── Write unit tests for conversions └── Use type hints (Python) or strong typing Don't: ├── Rely on implicit coercion ├── Ignore overflow/wrap-around ├── Cast without checking for None ├── Assume conversions always succeed ├── Use unsafe casts without validation └── Mix types in arithmetic without thought
Quick Reference
| Language | String to Int | Int to String | Safe Casting |
|---|---|---|---|
| Python | int("123") | str(123) | Try-except |
| JavaScript | parseInt("123") | String(123) | isNaN() check |
| Java | Integer.parseInt("123") | String.valueOf(123) | try-catch |
| C++ | stoi("123") | to_string(123) | try-catch |
| C | atoi("123") | sprintf() | Check return |
Type casting is a fundamental skill that every programmer must master. Understanding how different languages handle type conversion will help you write more robust, error-free code!