This is a note that Uncle Java thought about in Java to understand Elm's custom types. I'm not familiar with stag beetles.
Take Result
as an example of a custom type:
Elm Result definition
type Result error value
= Ok value
| Err error
An example of Java representation of the above Result
:
Result.java
interface Result {
class Ok<V> implements Result {
final V value;
Ok(V value) { this.value = value; }
}
class Err<E> implements Result {
final E error;
Err(E error) { this.error = error; }
}
}
--I skipped around the access modifier.
--I'm not doing my best because the purpose is not to ** reproduce ** custom types in Java.
――I really did my best (I gave Result
ʻE and
V`), but I stopped because it was troublesome.
Example of actually using the Java version Result
type:
Main.java
class Main {
public static void main(String[] args) {
show(validate("100")); // -> Ok: 100
show(validate("200hoge")); // -> Err:Please enter a number
}
/**
*Verify that text is a string consisting only of numbers.
* @param text The string to be validated.
* @Integer if return text consists only of numbers.parseInt(text)The result of
*Result set in the value field.Ok 。<br>
*If the text contains non-numeric characters"Please enter a number"To
*Result set in the error field.Err 。
*/
static Result validate(String text) { //"Elm understood from the basics" P.91 validate functions are the source
try {
var n = Integer.parseInt(text);
return new Result.Ok<>(n);
} catch (NumberFormatException e) {
return new Result.Err<>("Please enter a number");
}
}
/**
*Output the contents of result to standard output.
* @param result The value to output.
*/
static void show(Result result) {
if (result instanceof Result.Ok) {
var ok = (Result.Ok<Integer>) result;
System.out.println("Ok: " + ok.value);
} else if (result instanceof Result.Err) {
var err = (Result.Err<String>) result;
System.out.println("Err: " + err.error);
} else {
throw new RuntimeException("Mystery type is specified");
}
}
}
It's a code that doesn't look cool because it depends heavily on the ʻIntegerand
String specified in the type parameter, and it branches at the ʻinsutanceof
.
I guess I didn't do my best. ~~ In such an atmosphere. ~~
The current perception is that Elm's custom types look like this in Java. Originally, you should learn algebraic data types properly, but for the time being, my understanding has advanced (I feel), so Yoshi! I am.
Recommended Posts