Object.hashCode()的默认行为是返回对象的"地址",以便当且仅当a == b时,a.hashCode()== b.hashCode().如果超类已经定义了hashCode(),我如何在用户定义的类中获得此行为?例如:
class A {
public int hashCode() {
return 0;
}
}
class B extends A {
public int hashCode() {
// Now I want to return a unique hashcode for each object.
// In pythonic terms, it'd look something like:
return Object.hashCode(this);
}
}
Run Code Online (Sandbox Code Playgroud)
想法?
我遇到了any在 Typescript 中似乎无法避免的情况。这是一个反映我正在尝试做的事情的示例:
type NativeFn<A, B> = {
kind: 'native'
fn: (a: A) => B
}
type ComposeFn<A, B, C> = {
kind: 'compose'
f: Fn<B, C>
g: Fn<A, B>
}
type Fn<A, B> = NativeFn<A, B>
| ComposeFn<A, any, B> // <=== HERE
function evalfn<A, B>(fn: Fn<A, B>, arg: A): B {
switch (fn.kind) {
case 'native': return fn.fn(arg)
case 'compose': {
// intermediate has type "any", which is a drag.
const intermediate = evalfn(fn.g, arg)
return …Run Code Online (Sandbox Code Playgroud)