Kotlin Enum Class Anonymous class instance

Source: Internet
Author: User

There's something new in the enumeration class in Kotlin: The constant of an enumeration class can be seen as an anonymous class with the same name.

Since it is a class, it can be associated with a method

Check the code of the official website

If you have experienced the use of enumerations in other languages, you may be confused by this definition and explanation.

I'll give you an example and a result, and you'll be much clearer.

Enum class Protocolstate {
Waiting {
Override Fun signal () = talking
},

Talking {
Override Fun signal () = waiting
};

Abstract Fun Signal (): protocolstate
}

Fun Main (args:array<string>) {

Val ev:protocolstate = protocolstate.waiting
println (Ev.signal ())

}

Results

Talking

Finally:

Enumeration constants Support enumeration classes, support methods for overloading parent classes, enumeration constants, anonymous class rules, and constants, but constant anonymous classes and other components of the parent class are used ";" Separated

Well, maybe, you don't like the idea.

However, you may fall in love with Kotlin when you use it for practical development, after all, any innovation is definitely an implicit demand from the old road.

If you don't, it's likely that you're not daoxing enough.

Kotlin Enum Class Anonymous class instance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.