Getting Started with Kotlin
Try writing some Kotlin functions below. Remember that, like Haskell, every function has a type signature, where you specify the function name, the arguments, and the return type.
Syntax reminder:
Here's a reminder of the basic syntax for writing a function. You can run the code by clicking the green play button on the right.
fun successor(x: Int): Int = x + 1
fun main() {
val succ = successor(5)
println("Successor of 5 is: " + succ)
}
Try the following:
Write a function bigger()
to determine which of two integers is the largest. Edit the code below to complete the function and then hit play to test your solution. You don't need to write a main()
function here.
import org.junit.Test
import org.junit.Assert
class TestBigger() {
@Test fun firstIsBigger() {
Assert.assertEquals(4, bigger(4, 2))
}
@Test fun secondIsBigger() {
Assert.assertEquals(6, bigger(4, 6))
}
@Test fun bothTheSame() {
Assert.assertEquals(4, bigger(4, 4))
}
@Test fun handlesNegatives() {
Assert.assertEquals(4, bigger(-4, 4))
}
}
//sampleStart
fun bigger() = TODO()
//sampleEnd
Write a function biggestOfThree()
to determine which of three integers is the largest:
import org.junit.Test
import org.junit.Assert
class TestBiggestOfThree() {
@Test fun whenFirstIsBiggest() {
Assert.assertEquals(10, biggestOfThree(10, 5, 5))
}
@Test fun whenSecondIsBiggest() {
Assert.assertEquals(10, biggestOfThree(5, 10, 5))
}
@Test fun whenThirdIsBiggest() {
Assert.assertEquals(10, biggestOfThree(5, 5, 10))
}
@Test fun whenSomeAreNegative() {
Assert.assertEquals(10, biggestOfThree(10, -100, 5))
}
@Test fun whenAllTheSame() {
Assert.assertEquals(10, biggestOfThree(10, 10, 10))
}
}
//sampleStart
fun biggestOfThree() = TODO()
//sampleEnd
Write a recursive function fact()
to calculate n factorial:
import org.junit.Test
import org.junit.Assert
class TestFactorial() {
@Test fun factorialZeroIsOne() {
Assert.assertEquals(1, fact(0))
}
@Test fun factorialOneIsOne() {
Assert.assertEquals(1, fact(1))
}
@Test fun factorialThreeIsSix() {
Assert.assertEquals(6, fact(3))
}
@Test fun factorialTen() {
Assert.assertEquals(3628800, fact(10))
}
}
//sampleStart
fun fact() = TODO()
//sampleEnd
Write a recursive function fib()
to calculate the nth Fibonacci number:
import org.junit.Test
import org.junit.Assert
class TestFibonacci() {
@Test fun firstTermIsOne() {
Assert.assertEquals(1, fib(1))
}
@Test fun secondTermIsOne() {
Assert.assertEquals(1, fib(2))
}
@Test fun thirdTermIsTwo() {
Assert.assertEquals(2, fib(3))
}
@Test fun fourthTermIsThree() {
Assert.assertEquals(3, fib(4))
}
@Test fun fifthTermIsFive() {
Assert.assertEquals(5, fib(5))
}
}
//sampleStart
fun fib() = TODO()
//sampleEnd