I'm trying to find a clean way to build a full nam...
# codereview
e
I'm trying to find a clean way to build a full name out of nullable components. I'm sure you can do better than I did:
Copy code
class Person (val personalName: String?, val middleInitial: String?, val familyName: String?) {
    override fun toString(): String {
        val nameParts = mutableListOf<String>()
        if (personalName != null) nameParts.add(personalName)
        if (middleInitial != null) nameParts.add(middleInitial)
        if (familyName != null) nameParts.add(familyName)
        return nameParts.joinToString(separator = " ")
    }
}
e
listOfNotNull() is a standard library function
Copy code
listOfNotNull(personalName, middleInitial, familyName).joinToString(" ")
(but of course you wouldn't actually do this, right? https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/)
e
I'm trying to motivate
null
for an introductory programming class that uses Kotlin. I was planning to mention that great article you link to and examples of people who don't have various components.
I'm not sure that name properties are compelling, since you could argue for using the empty string. The students haven't seen lists yet, so I can't use them in the example.
@ephemient If you don't think name components should be joined together, what do you advocate (independent of whether
null
is used)?
e
for names specifically? the only reliable way to determine a user's full name without cultural assumptions is to ask them
for an exercise, sure… although without pointers I don't think there is really any good motivation for why references can be null
e
Yeah, I'm reaching the same conclusion. I have introduced classes so could use a family tree that tops out at Adam and Eve.
I ended up creating a
Friend
class and showing why you can't do:
Copy code
val calvin = Friend("Calvin", bestFriend = hobbes)
val hobbes = Friend("Hobbes", bestFriend = calvin)