0

This small code gives error: unresolved reference: make :

sealed class Color () {
    object Red : Color()
    object Blue : Color()

   override fun toString(): String =
       when (this) {
           is Red -> "Red"
           is Blue -> "Blue"
       else -> "Error"
       }

   fun make(name: String): Color {
       return when (name) {
           "Red" -> Red 
           "Blue" -> Blue
       else -> throw Exception ("Error unkown color '$name'") 
       }
   }
}   

fun main(args: Array<String>) {
    val color = Color.make("Red")
    println (color.toString())
}

I tried val color = make("Red") and got the same error. Why ? What I have to do to fix that ?

smac89
  • 39,374
  • 15
  • 132
  • 179
Emile Achadde
  • 1,715
  • 3
  • 10
  • 22
  • 2
    Your `make` is an instance method, ie you need an instance of `Color` to call it on: like `Color().make("red")` this works because `Color` has a no arg constructor. You can put `make` in the companion object if you wish to invoke it like you did in your example. – al3c Feb 27 '20 at 17:38

1 Answers1

2

Put the function in a companion object:

sealed class Color() {
    object Red : Color()
    object Blue : Color()

    override fun toString(): String = when (this) {
        is Red -> "Red"
        is Blue -> "Blue"
        else -> "Error"
    }

    companion object {
        fun make(name: String): Color = when (name) {
            "Red" -> Red
            "Blue" -> Blue
            else -> throw Exception("Error unkown color '$name'")
        }
    }
}

Kotlin Playground

smac89
  • 39,374
  • 15
  • 132
  • 179
  • I did it and got the same error in the main function: val color = make("Red") error: unresolved reference: make – Emile Achadde Feb 27 '20 at 18:03
  • 1
    @EmileAchadde you are probably doing something else wrong. It works perfectly fine for me. Make sure you use `val color = Color.make("Red")` – smac89 Feb 27 '20 at 18:05
  • You are right I did not specified Color in val color = Color.make("Red") that works fine ! – Emile Achadde Feb 27 '20 at 18:13