简体   繁体   中英

how to set custom return type nullable in kotlin

I made a personal data type "email" how can I make this type nullable in value.

For example.

private lateinit var a: email?

or

fun makeEmailAddress(a: String): email? {
   // TODO
}

lateinit var uses nulls behind the scenes to represent the uninitialized value, so they cannot be of nullable types from the point of view of the program. That said, this limitation is in general not a problem because most of the time the point of using lateinit var is so that you can use non-null types while still delaying initialization.

If you need a nullable property, you can simply drop the lateinit modifier and initialize it to null when declaring it:

private var a: Email? = null

For the function declaration, the return type Email? should just work:

fun makeEmailAddress(a: String): Email? {
   // return whatever you need here, either null or an Email instance
}

Note that types are capitalized in Kotlin by convention, so I suggest you rename email to Email (I used the capitalized version in the sample code above).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM