【HarmonyOS】鸿蒙中Interface实例实现的书写格式
【HarmonyOS】鸿蒙中Interface实例实现的书写格式
ArkTS中Interface的定义和实现:
一、接口的定义:
TestInterface .ets
// 添加export 在其他类才能导入,需要特别注意
export interface TestInterface {// 与java等语法不同的点,定义函数时通过 ()=> void 来表达。onTest: (s: string, n: number) => void// => 箭头后表示返回值onTest2: (s: string) => string}
有些同学在定义上,依旧与java等语法相同,在接口实现时就会报错,提示:
Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)
二、接口的实现:
当接口定义后,我们在需要调用实现interface接口处进行实例化接口的实现:
1.我们可以直接创建全局对象进行接口的实例化:
private mTestInterface: TestInterface = {onTest: (s: string, n: number) => {console.log(this.TAG, "s: " + s + " n:" + n);},onTest2: (s: string) => {return s;}}this.mTestInterface.onTest("test", 1);this.mTestInterface.onTest2("1")
2.亦或者通过匿名的形式进行接口的实现:
let testCallBack: TestInterface = {onTest: (s: string, n: number) => {console.log(this.TAG, "s: " + s + " n:" + n);},onTest2: (s: string) => {return s;}}testCallBack.onTest("test", 1);
DEMO示例:
import { TestInterface } from '../interface/TestInterface';
struct InterfacePage {private TAG: string = "InterfacePage";aboutToAppear(): void {this.mTestInterface.onTest("test", 1);}private mTestInterface: TestInterface = {onTest: (s: string, n: number) => {console.log(this.TAG, "s: " + s + " n:" + n);},onTest2: (s: string) => {return s;}}build() {Row() {Text(this.mTestInterface.onTest2("1")).fontSize(50)}.height('100%').width('100%').justifyContent(FlexAlign.Center)}
}export interface TestInterface {onTest: (s: string, n: number) => voidonTest2: (s: string) => string}