Kotlin Model Definitions

Hello! Recent joiner here and first time visiting the forums, so I apologise if this isn't the right place to post this!

The model definitions for Kotlin questions aren't what you'd expect in the Kotlin world.

For example, in question 617:

/**
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int = 0) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */

Needs to be used as follows:

val x = TreeNode(0)
x.left = TreeNode(1)
x.right = TreeNode(2)
val v = x.`val`

There's one property defined in the constructors (when they all can be) and val is a bit of an awkward property name in Kotlin as it's a keyword and needs to be surrounded with `.

A more idiomatic definition would be as follows:

data class TreeNode(
    var `val`: Int = 0,
    var left: TreeNode? = null,
    var right: TreeNode? = null
)

Or even

data class TreeNode(
    var value: Int = 0, // avoid the val keyword
    var left: TreeNode? = null,
    var right: TreeNode? = null
)

This could then be used as follows:

val x = TreeNode(0)
val y = TreeNode(0, null, TreeNode(0))
val z = TreeNode(
    value = 0,
    right = TreeNode()
)
// etc

I appreciate that this may be fairly difficult (if not impossible) to fix retrospectively, but it would be awesome if it could be considered for future questions.

Comments (1)