private final int servings; // required private final int calories; optional private final int fat; // optional private final int sodium; // optional private final int carbohydrate; // optional } • Telescoping Constructor Pattern • JavaBeans Pattern Item 2: “Consider a builder, when faced with many constructor parameters”
void main(String[] args) { // primitive long instead of the Long reference type long sum = 0L; for (long i = 0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); } } Fast Java Program
float, double, byte, … Reference Types: Integer, Long, Float, Double, String, … • Primitives hold values • Primitives hold only functional values • Primitives are more time- and space-efficient
Item 5: “Avoid creating unnecessary Objects” • Item 49: “Prefer primitive types to reference types” ◦ Always use primitives unless you are forced to use reference types in ▪ Collections ▪ Type arguments in generic classes
Most of the times, Java primitive types are generated • Exceptions: ◦ objects in collections, ◦ type arguments in generic classes ◦ nullable types! // So we will still have performance issues if we use Long? var sum: Long? = 0L
kind of type we use • Kotlin Compiler makes that decision • Compiler sticks to advice of Effective Java • We cannot make the mistakes you can make in Java, that Effective Java points out like creating unnecessary objects + =
“Obey the general contract when overriding equals” • Item 9 “Always override hashCode when you override equals” • Item 10 “Always override toString()” • Item 11 “Override clone judiciously” • More than pages 20 pages
to create proper immutable value objects in Java • how to properly implement toHashCode(), equals() and clone() • in Kotlin, the compiler is doing that for us • data class + =
inheritance • shows how to achieve it with forwarding classes • Kotlin supports composition natively with class delegation • requires zero boiler plate code + =
bar = 1; class Nested { public int foo() { return bar; } } } non-static public class Outer { private int bar = 1; static class Nested { public int foo() { return 2; } } } static
{ private val bar: Int = 1 class Nested { fun foo() = 2 } } static class Outer { private val bar: Int = 1 inner class Nested { fun foo() = bar } } non static
Check parameters for validity • Chapter 9: Exceptions ◦ Avoid unnecessary use of checked exceptions More Information in my Blogpost Series on Medium: medium.com/@lukleDev