Skip to content

Instantly share code, notes, and snippets.

@trfiladelfo
Last active April 27, 2024 18:59
Show Gist options
  • Save trfiladelfo/92edd1cad568ae6bae6c026dac52dff2 to your computer and use it in GitHub Desktop.
Save trfiladelfo/92edd1cad568ae6bae6c026dac52dff2 to your computer and use it in GitHub Desktop.
Validador de CPF em Kotlin
fun isCPF(document: String): Boolean {
if (document.isEmpty()) return false
val numbers = document.filter { it.isDigit() }.map {
it.toString().toInt()
}
if (numbers.size != 11) return false
//repeticao
if (numbers.all { it == numbers[0] }) return false
//digito 1
val dv1 = ((0..8).sumOf { (it + 1) * numbers[it] }).rem(11).let {
if (it >= 10) 0 else it
}
val dv2 = ((0..8).sumOf { it * numbers[it] }.let { (it + (dv1 * 9)).rem(11) }).let {
if (it >= 10) 0 else it
}
return numbers[9] == dv1 && numbers[10] == dv2
}
@trfiladelfo
Copy link
Author

trfiladelfo commented May 8, 2018

v1: Código para validação do CPF.
v2: Fiz algumas alterações para tornar o código mais enxuto.
v3: Ajuste para quando os dígitos 1 e 2 forem maiores que 10 ser considerado como o número 0.
v4: Sugestão do @lmint1 e deixando o código Kotlin puro e com as funções atuais

@rsalomao2
Copy link

Vlw mano!

@lmint1
Copy link

lmint1 commented Jun 17, 2021

Show man, que tal fazer assim na repetição:

//repeticao  
if (numbers.all { it == numbers[0] }) return false  

@trfiladelfo
Copy link
Author

trfiladelfo commented Jun 18, 2021

Show man, que tal fazer assim na repetição:

//repeticao  
if (numbers.all { it == numbers[0] }) return false  

Boa, valeuuuuu, vou aproveitar para atualizar um pouco e deixar ainda mais enxuto
v4: Sugestão do @lmint1 e deixando o código Kotlin puro e com as funções atuais

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment