broxigar
broxigar

Reputation: 3

Function Implementation - Kotlin

First of all, i'm new to the programming world. I currently take multiple online course to help me learn programming in Kotlin. In one of the course, i kinda hit a road block. I can't continue unless i solve the problem. I know the problem is suppose to be not that difficult, but I find it hard to conceptualize the what the problem really is. I've been racking my brains over the problem for the past 2 days, been searching on the internet with no result. (Maybe it's because i don't really understand what to search)

Finally i decided i would try to ask the question here. (I've been using this website as one of my go-to site to help me solve programming problem i got from the course)

So here is the problem:

There is this class:

class Site(val address: String, val foundationYear: Int)

Implement the makeReddit() function that returns a Site with the reddit.com address and the foundation year of 2005.

Here's my attempt to solve the problem:

class Site(val address: String, val foundationYear: Int) {
    fun makeReddit(address: String, foundationYear: Int): Site {
        return reddit
    }
    private val reddit = makeReddit("reddit.com", 2005)
}

Thank you.

Upvotes: 0

Views: 63

Answers (1)

Tenfour04
Tenfour04

Reputation: 93571

Here's why your code doesn't make sense. You have a class named Site that presumably can be used to describe any web site. So it should not have a property for a specific site named reddit, because then every single instance of the class is carrying the reddit property.

Your function makeReddit should not have parameters for address and year, because it's for making the specific site "reddit.com" with a specific year 2005.

Also, your function returns the value of a property, but the property is initialized by calling that function, so this is a circular dependency. Both the function and the property will just end up returning null. You never call the Site constructor anywhere, so no Site instance is ever created.

And since the function doesn't do anything internal to any specific Site, but instead creates a new Site instance, it should not be defined inside the Site class.

To step back and define the problem, you need a function that creates a Site with specific values of address and year (not input parameters). Since it creates a Site, it should not be a member function of Site, so it should be defined at the top level (it could also be in a companion object, but don't worry about that for now).

So it should look like this:

class Site(val address: String, val foundationYear: Int)

fun makeReddit(): Site {
    return Site("reddit.com", 2005)
}

Upvotes: 2

Related Questions