Published on

Kotlin Class with Constructor Fields that are not Bean Properties


One of the most awesome things with Kotlin is how it removes huge amounts of boilerplate code when defining beans. If you want a bean field which is mutable you define it as a var which means it will have getters, setters and constructor injection. If on the other hand you want a bean field that is immutable you make it a val, this will force you to constructor inject it and provide a getter and no setter for you to use. But what if you simply want to pass a value into the constructor to be used internally in the class but not be exposed again and not be a bean field? You simply do not define it as a val or a var. The only caveat with this approach is that your class cannot be a data class.

The code below illustrates this best:

package com.test

class ClassWithNoneBeanFields(someNoneBeanField: String, val immutableBeanField: String, var mutableBeanField: String) {
    private val upperCasedField = someNoneBeanField.toUpperCase()

    override fun toString(): String {
        return "ClassWithNoneBeanFields(immutableBeanField='$immutableBeanField', mutableBeanField='$mutableBeanField', upperCasedField='$upperCasedField')"

fun main(args: Array<String>) {

    val noneBeanFields = ClassWithNoneBeanFields("bLah", "John", "Smith")

    noneBeanFields.mutableBeanField = "Doe"
ClassWithNoneBeanFields(immutableBeanField='John', mutableBeanField='Smith', upperCasedField='BLAH')
ClassWithNoneBeanFields(immutableBeanField='John', mutableBeanField='Doe', upperCasedField='BLAH')