重写具有通用界面类型 Bound 和隐式的方法。

huangapple 未分类评论57阅读模式
标题翻译

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](&quot;John&quot;)

Also code have to show the result:

def show: Conditions[String] =
    new Conditions[String] {
        def nameIs(name: String): String = s&quot;name is $name&quot;
        def ageUpperThan(age: Int): String = s&quot;age upper $age&quot;
    }

println(isJohn[String](show))

Could yo help me to rewrite the methods nameIs and isJohn?

I have a problem with implicit and [T: Conditions]

huangapple
  • 本文由 发表于 2020年3月4日 02:47:53
  • 转载请务必保留本文链接:https://java.coder-hub.com/60513741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定