Ok, I fixed it. It's not too much uglier with proper Option protection...
importarrow.core.Optionimportarrow.core.getOrElsedata classStudent(valname:String,valfives:Int,valtens:Int,valtwenties:Int)privatevalStudent.total:Intget()=fives*5+tens*10+twenties*20sealedclassStudentAccumulator{abstractvalmoney:Option<Int>}objectEmpty:StudentAccumulator(){overridevalmoney=Option.empty<Int>()}data classErrorFound(valmessage:String):StudentAccumulator(){overridevalmoney=Option.empty<Int>()}data classMaxFound(valname:String,overridevalmoney:Option<Int>):StudentAccumulator(){constructor(student:Student):this(student.name,Option.just(student.total))}data classTieFound(overridevalmoney:Option<Int>):StudentAccumulator(){constructor(student:Student):this(Option.just(student.total))}fungenerateStudentFolder(compareFn:(StudentAccumulator,Student)->Option<Int>)={acc:StudentAccumulator,student:Student->when(acc){isErrorFound->accisEmpty->MaxFound(student)isMaxFound->acc.consider(student,compareFn)isTieFound->acc.consider(student,compareFn)}}funMaxFound.consider(student:Student,compareFn:(StudentAccumulator,Student)->Option<Int>)=compareFn(this,student).map{result->when(result){-1->MaxFound(student)0->TieFound(student)else->this}}.getOrElse{ErrorFound("Bad comparison.")}funTieFound.consider(student:Student,compareFn:(StudentAccumulator,Student)->Option<Int>)=compareFn(this,student).map{result->when(result){-1->MaxFound(student)0->ErrorFound("More than one maximum")else->this}}.getOrElse{ErrorFound("Bad comparison.")}funIterable<Student>.findMax()=fold(EmptyasStudentAccumulator,generateStudentFolder{a,b->a.money.map{it.compareTo(b.total)}})funIterable<Student>.findMaxName():String{returnwhen(valresult=findMax()){isErrorFound->throwError(result.message)isEmpty->throwError("No max found")isMaxFound->result.nameisTieFound->"all"}}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Ok, I fixed it. It's not too much uglier with proper Option protection...