标题翻译
Rewrite methods with generic with interface type Bound and implicit
问题
interface Conditions<T> {
    T nameIs(String color);
    T ageUpperThan(int upper);
}
class EmployeeConditions implements Conditions<EmployeeConditions> {
    @Override
    public EmployeeConditions nameIs(String name) {
        // Implement the logic for checking the name
        return this;
    }
    @Override
    public EmployeeConditions ageUpperThan(int upper) {
        // Implement the logic for checking the age
        return this;
    }
}
class Employee {
    // Employee class implementation
}
class Main {
    public static EmployeeConditions nameIs(String color) {
        return new EmployeeConditions().nameIs(color);
    }
    public static EmployeeConditions isJohn() {
        return nameIs("John");
    }
    public static void main(String[] args) {
        EmployeeConditions show = new EmployeeConditions() {
            @Override
            public EmployeeConditions nameIs(String name) {
                return super.nameIs(name);
            }
            @Override
            public EmployeeConditions ageUpperThan(int age) {
                return super.ageUpperThan(age);
            }
        };
        System.out.println(isJohn().nameIs("John"));
    }
}
Please note that Java does not have the exact equivalent of Scala's implicit parameter and context bounds ([T: Conditions]). In Java, you'll need to explicitly pass the concrete implementation of the Conditions interface to the methods that require it.
英文翻译
I have a trait with generic and two alternative methods for checking age and name of employee.
trait Conditions[T] {
    def nameIs(color: String): T
    def ageUpperThan(upper: Int): T
}
def nameIs[T](color: String)(implicit fi: Conditions[T]): T = fi.nameIs(color)
I want to rewrite all these Scala code to Java which let me generate a concrete conditions for example to check the name is John.
def isJohn[T: Conditions]: T = nameIs[T]("John")
Also code have to show the result:
def show: Conditions[String] =
    new Conditions[String] {
        def nameIs(name: String): String = s"name is $name"
        def ageUpperThan(age: Int): String = s"age upper $age"
    }
println(isJohn[String](show))
Could yo help me to rewrite the methods nameIs and isJohn?
I have a problem with implicit and [T: Conditions]
专注分享java语言的经验与见解,让所有开发者获益!



评论