Java vs Kotlin接口声明

时间:2017-07-09 23:52:11

标签: java interface kotlin

说我有这个Java和Kotlin接口:

import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import * as widgetsActions from '../js/actions/widgetsActions';
import Dashboard from './dashboard/Dashboard';
import style from './App.scss';

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      widgets: this.props.widgets,
    };
  }

  componentWillMount() {
    if (JSON.stringify(this.state.widgets) === JSON.stringify({})) {
      this.props.loadWidgets();
    }
  }

  componentWillReceiveProps({ widgets }) {
    if (widgets !== this.props.widgets) {
      this.setState({ widgets });
    }
  }

  render() {
    return (
      <div className={style.app}>
        {(JSON.stringify(this.state.widgets) !== JSON.stringify({})) &&
        <div>
          <Dashboard widgets={this.state.widgets} />
        </div>
        }
     </div>
    );
  }
}

App.propTypes = {
  loadWidgets: PropTypes.func.isRequired,
  widgets: PropTypes.shape({
    value1: PropTypes.number,
    value2: PropTypes.number,
    value3: PropTypes.number,
  }).isRequired,
};

const mapStateToProps = state => (
  {
    widgets: state.widgets,
  }
);

const mapDispatchToProps = dispatch => (
  {
    loadWidgets: () => dispatch(widgetsActions.loadWidgets()),
  }
);

export default connect(mapStateToProps, mapDispatchToProps)(App);

为什么我不能在没有构造函数的情况下创建Kotlin接口的实例?

public interface JavaInterface {

    void onTest();
}

interface KotlinInterface {

    fun onTest()
}

为什么我不像第一个例子那样用// this is okay val javaInterface: JavaInterface = JavaInterface { } // compile-time exception: interface does not have constructor val kotlinInterface1: KotlinInterface = KotlinInterface { } // this is okay val kotlinInterface2: KotlinInterface = object : KotlinInterface { override fun onTest() { } } 创建KotlinInterface的实例?

1 个答案:

答案 0 :(得分:1)

那是因为Kotlin只为Java接口提供了SAM(#34;单一抽象方法&#34;)。这是design的方式。 docs上也有一些信息:

  

另请注意,此功能仅适用于Java互操作;由于Kotlin具有适当的函数类型,因此不需要将函数自动转换为Kotlin接口的实现,因此不受支持。

Related issue