Skip to main content

TIL - Kotlins' truly OOP

Ayman Patel

Ayman Patel

Back End Engineer @ Mastercard

Links

  • Type Witness

It ensures OOP by 3 virtues

  1. Immutable

Use val not var

  1. Not null

  2. No static access

Static access is BAD for OOP since OOP originally is about object-passing and static objects makes it a global stateful object.

But, Junit 4 @Before is staticl so if you want to write a ot of boilerplate to allow static instantiation

class RepositoryTest {
companion object { // for `static` and `@JvmStatic`
@JvmStatic private lateinit var mongo: GenericContainer // var is used every test method
@JvmStatic private lateinit var repo: Repository // variables might bring null values; so `lateinit` is null workaround.
@BeforeClass @JvmStatic
fun initiiazlize() {
mongo = startMpngoContainer()
repo = Repository(mongo.host, mongo.port)
}
}
}

Type Witness in Generic#

Suppose you want to invoke the method processStringList with an empty list. In Java SE 7, the following statement does not compile:

processStringList(Collections.emptyList());

The Java SE 7 compiler generates an error message similar to the following:

processStringList(Collections.<String>emptyList());

This is no longer necessary in Java SE 8. The notion of what is a target type has been expanded to include method arguments, such as the argument to the method processStringList. In this case, processStringList requires an argument of type List. The method Collections.emptyList returns a value of List, so using the target type of List, the compiler infers that the type argument T has a value of String. Thus, in Java SE 8, the following statement compiles:

processStringList(Collections.emptyList());