this is java code
@Data
public class UserBaseVo {
@NotNull
@Length(min = 6, max = 12)
private String username;
@NotNull
@Min(0)
@Max(1)
private Integer sex;
@NotNull
@Min(0)
@Max(1)
private Integer status;
}
@EqualsAndHashCode(callSuper = true)
@Data
public class UserUpdateVo extends UserBaseVo {
@NotNull
private Long id;
}
@RestController
public class UserController {
@PostMapping("create")
public Res<Boolean> createUser(@RequestBody @Valid UserBaseVo baseVo) {
//service.create
return ok(true);
}
@PostMapping("update")
public Res<Boolean> updateUser(@RequestBody @Valid UserUpdateVo updateVo) {
//service.create
return ok(true);
}
}
This way I can verify different objects when I create and modify the user. The code is simple. But kotlin can’t be done as succinctly as this. Look at the kotlin code
// method 1
KtUserUpdateVo
open class KtUserBaseVo(
@Length(min = 6, max = 12)
var username: String,
@Min(0)
@Max(1)
var sex: Int,
@Min(0)
@Max(1)
var status: Int,
)
class KtUserUpdateVo(var id: Long, username: String, sex: Int, status: Int) : KtUserBaseVo(username, sex, status)
// method 2
open class KtUserBaseVo {
@NotNull
@Length(min = 6, max = 12)
var username: String? = null
@NotNull
@Min(0)
@Max(1)
var sex: Int? = null
@NotNull
@Min(0)
@Max(1)
var status: Int? = null
}
class KtUserUpdateVo : KtUserBaseVo() {
@NotNull
var id: Long? = null
}
method 1: This approach defines redundant fields in the construction of
method 2: This approach defines unnecessary nullable types because none of them can be nullable, thus losing kotlin’s non-nullable nature
kotlin both of these methods have shortcomings, do you have any better solutions, thank you very much
ygq is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0