Reputation: 393
Is it possible to use an enum as a parameter of a function declaration within an interface? For example have:
class FloatingToastDialog(val messageType: FloatingToastType) {
companion object {
enum class FloatingToastType { Alert, Warning, Error }
}
...
}
I would like to declare in an interface a function that takes an enum as input parameter like so:
interface SecurityCallbacks {
fun showFloatingToast(message: String, msgType: FloatingToastType)
}
but the compiler fails to import the enum by saying Unresolved reference: FloatingToastType
Is it possible to do that without using ordinals or other such escamotages?
Upvotes: 3
Views: 240
Reputation: 1002
You have to reference the enum inside a companion object this way: classame.Companion.enumtype
so, in your case, you can declare the interface like that :
interface SecurityCallbacks {
fun showFloatingToast(message: String, msgType: FloatingToastDialog.Companion.FloatingToastType)
}
Alternativaly you can declare the enum inside the class FloatingToastDialog, not in the inner companion object and use it in the interface like that:
interface SecurityCallbacks {
fun showFloatingToast(message: String, msgType: FloatingToastDialog.FloatingToastType)
}
Upvotes: 2
Reputation: 170723
If you declare it this way, you have to refer to it as
fun showFloatingToast(message: String, msgType: FloatingToastDialog.Companion.FloatingToastType)
or
import FloatingToastDialog.Companion.FloatingToastType
...
fun showFloatingToast(message: String, msgType: FloatingToastType)
You can declare it inside the class directly and remove Companion
:
class FloatingToastDialog(val messageType: FloatingToastType) {
enum class FloatingToastType { Alert, Warning, Error }
...
}
fun showFloatingToast(message: String, msgType: FloatingToastDialog.FloatingToastType)
Upvotes: 2
Reputation: 627
I'm from C# background but I think it'll be helpfull for you. I'm able to do it this way.If I skipped anything(or I need to tell java solution) feel free to point out.
using System;
public enum FloatingToastType {
Alert,
Warning,
Error
}
interface SecurityCallbacks {
void showFloatingToast(String message, FloatingToastType msgType);
}
public class Program
{
public static void Main()
{
Console.WriteLine("Main");
FloatingToastDialog obj = new FloatingToastDialog();
obj.showFloatingToast("Alert", FloatingToastType.Alert);
}
}
class FloatingToastDialog : SecurityCallbacks
{
public void showFloatingToast(String message, FloatingToastType messageType)
{
Console.WriteLine(message + " " + messageType.ToString());
}
}
It Gives the Output: Main Alert Alert
Upvotes: 0
Reputation: 113
I think you have to declare the enum outside the class/companion object as package element, that should work. Also the enum should be in the interface.
Upvotes: 1