Kotlin Basics: A Beginner’s Guide
val name: String = “John”
val age: Int = 25
Introduction to Kotlin
1. Variables and Data Types
- Immutable Variables (val)
val testCaseName: String = “Login Test”
val maxRetries: Int = 3
- Mutable Variables (var)
var location: String = “New York”
location = “Los Angeles” // Allowed because ‘location’ is mutable
- Type Inference
val testStatus = “Passed” // Kotlin infers the type as String
var retryCount = 0 // Kotlin infers the type as Int
Why it matters: Immutable variables (val
) and mutable variables (var
) play crucial roles in test automation. Immutable variables ensure consistency and prevent unexpected changes during test execution, while mutable variables allow flexibility where needed
2. Functions
Functions in Kotlin are defined using the fun
keyword. Kotlin supports single-expression functions, making the code concise and readable.
- Basic Function
fun greetTester(name: String): String {
return “Hello, $name! Ready to test?”
}
println(greetTester(“Mohammed”)) // Output: Hello, Mohammed! Ready to test?
- Single-Expression Function
fun addTestCases(a: Int, b: Int) = a + b
println(addTestCases(5, 3)) // Output: 8
- Default and Named Arguments
fun displayTestResult(testName: String = “Unknown Test”, result: String) {
println(“$testName: $result“)
}
displayTestResult(result = “Passed”) // Output: Unknown Test: Passed
displayTestResult(“Login Test”, result = “Failed”) // Output: Login Test: Failed
3. Control Flow
Kotlin provides several control flow structures, including if
, when
, for
, and while
.
- If Expression
val maxRetries = 3
val retries = 2
val canRetry = if (retries < maxRetries) “Yes” else “No”
println(“Can retry? $canRetry“)
- When Expression
val testScore = 85
val testResult = when(testScore) {
in 90..100 -> “Excellent”
in 80..89 -> “Good”
else -> “Needs Improvement”
}
println(“Test result: $testResult“)
- For Loop
val testCases = listOf(“Login Test”, “Signup Test”, “Profile Update Test”)
for (testCase in testCases) {
println(“Executing $testCase“)
}
- While Loop
var testAttempts = 0
while (testAttempts < 3) {
println(“Attempt #${testAttempts + 1}“)
testAttempts++
}
- Do-While Loop
var retries = 0
do {
println(“Retry #${retries + 1}“)
retries++
} while (retries < 3)
Why it matters: Control flow structures are essential in test automation for managing different test scenarios. For instance, you might want to check if a test case passes or fails:
val testCaseResult = “pass”
val message = when(testCaseResult) {
“pass” -> “Test case passed successfully”
“fail” -> “Test case failed”
else -> “Unknown test case result”
}
println(message)
4. String Templates
Kotlin makes it easy to work with strings using string templates.
- Basic String Templates
val testName = “Login Test”
println(“Starting $testName…”) // Output: Starting Login Test…
- Expression Templates
val expected = 5
val actual = 3
println(“Expected: $expected, Actual: $actual“) // Output: Expected: 5, Actual:
Why it matters: String templates make it easy to log test results and other information during test execution. For example:
val testName = “Login Test”
val status = “passed”
println(“The $testName has $status.”) // Output: The Login Test has passed.
5. Ranges and Collections
Ranges and collections are powerful tools in Kotlin for handling data sequences.
- Ranges
for (attempt in 1..3) {
println(“Test attempt #$attempt“)
}
for (priority in 1 until 5) {
println(“Priority level: $priority“)
}
for (priority in 5 downTo 1) {
println(“Priority level: $priority“)
}
for (step in 1..5 step 2) {
println(“Step: $step“)
}
- Collections
val testCaseList = listOf(“Login Test”, “Signup Test”, “Profile Update Test”)
for (testCase in testCaseList) {
println(“Executing $testCase“)
}
val mutableTestCaseList = mutableListOf(“Login Test”, “Signup Test”)
mutableTestCaseList.add(“Profile Update Test”)
println(mutableTestCaseList) // Output: [Login Test, Signup Test, Profile Update Test]
val testCaseMap = mapOf(1 to “Login Test”, 2 to “Signup Test”, 3 to “Profile Update Test”)
for ((id, name) in testCaseMap) {
println(“Test Case $id: $name“)
}
val mutableTestCaseMap = mutableMapOf(1 to “Login Test”, 2 to “Signup Test”)
mutableTestCaseMap[3] = “Profile Update Test”
println(mutableTestCaseMap) // Output: {1=Login Test, 2=Signup Test, 3=Profile Update Test}
Why it matters: Collections in Kotlin are powerful for managing test data. For example, a list of test cases can be iterated over to execute each one:
val testCases = listOf(“Login Test”, “Signup Test”, “Profile Update Test”)
for (testCase in testCases) {
println(“Executing $testCase“)
}
6. Null Safety
Why it matters: Collections in Kotlin are powerful for managing test data. For example, a list of test cases can be iterated over to execute each one:
- Nullable and Non-Nullable Types
var nonNullableTestResult: String = “Passed”
// nonNullableTestResult = null // Compilation error
var nullableTestResult: String? = “Failed”
nullableTestResult = null // No error
- Safe Calls and Elvis Operator
val testResultLength: Int? = nullableTestResult?.length // Safe call
println(testResultLength)
val testResultLengthOrDefault: Int = nullableTestResult?.length ?: 0 // Elvis operator
println(testResultLengthOrDefault)
- Smart Casts
fun printTestResultLength(result: Any) {
if (result is String) {
println(result.length) // Smart cast to String
}
}
Why it matters: Kotlin’s null safety features help prevent common runtime errors in test scripts, ensuring more reliable test execution. For example:
var testResult: String? = “Success”
testResult = null // Safe to assign null
val message = testResult ?: “Test result is unknown”
println(message) // Output: Test result is unknown
Conclusion
Follow us on Medium: EspressoLab Medium
Thank you for reading!