Gabriel Luchtenberg
02/14/2023, 1:20 AMval email : Email = "<mailto:gabrie@test.co|gabrie@test.co>"
Bryan Buschmann
02/14/2023, 1:31 AMGabriel Luchtenberg
02/14/2023, 1:31 AMBryan Buschmann
02/14/2023, 1:38 AMval primaryIdentity = Email("<mailto:gabrie@test.co|gabrie@test.co>")
be more concise and more explicit at the same time?Bryan Buschmann
02/14/2023, 1:39 AMAndrew O'Hara
02/14/2023, 3:05 AM"<mailto:gabriel@test.co|gabriel@test.co>".toEmail()
where
fun String.toEmail(): Email = TODO("validate and init email")
Bryan Buschmann
02/14/2023, 3:13 AMJosh Eldridge
02/14/2023, 3:28 AMval email : Email = "<mailto:gabrie@test.co|gabrie@test.co>"
I'd think someone type aliased a string as Email
for some reason, not super readable up frontStephan Schröder
02/14/2023, 8:09 AM@JvmInline
value class Email(val value: String) {
init {
require(value.contains('@')) {"email value $value doesn't contain '@'"}
}
}
At runtime the compiler will have gotten rid of the Email class in most cases, so you have the performance of only handling a String but the type safety of a wrapper type approach.
But as mentioned before the wrapping of your type around a string isn't invisible, so it's either Email("<mailto:gabrie@test.co|gabrie@test.co>")
or you write an extension function (this time without the validation, since that's taken care of in the init-block).
fun String.toEmail(): Email = Email(this)
For more info on inline classes see https://kotlinlang.org/docs/inline-classes.htmlphldavies
02/14/2023, 10:07 AMvalue class Email implicit constructor(val value: String)
🤔Stephan Schröder
02/15/2023, 7:49 AMoverwrite
keyword, if you want tail recursion to be applied to a function that would allow it, you still have to add tailrec
, if you want to convert number types, e.g. convert an Int to Long, you still have to invoke toLong()
. Notice that this is even the case for the safe direction Int -> Long.
I googled a bit a found an old discussion from 2015, coming to the same conclusion https://discuss.kotlinlang.org/t/union-types/77/10
Of course this is not a primary source (from JetBrains itself), but just another dev coming to the same conclusion.